core/iter/traits/iterator.rs
1use super::super::{
2 ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, FlatMap,
3 Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, MapWindows, Peekable,
4 Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, TrustedRandomAccessNoCoerce,
5 Zip, try_process,
6};
7use super::TrustedLen;
8use crate::array;
9use crate::cmp::{self, Ordering};
10use crate::marker::Destruct;
11use crate::num::NonZero;
12use crate::ops::{ChangeOutputType, ControlFlow, FromResidual, Residual, Try};
13
14fn _assert_is_dyn_compatible(_: &dyn Iterator<Item = ()>) {}
15
16/// A trait for dealing with iterators.
17///
18/// This is the main iterator trait. For more about the concept of iterators
19/// generally, please see the [module-level documentation]. In particular, you
20/// may want to know how to [implement `Iterator`][impl].
21///
22/// [module-level documentation]: crate::iter
23/// [impl]: crate::iter#implementing-iterator
24#[stable(feature = "rust1", since = "1.0.0")]
25#[rustc_on_unimplemented(
26 on(
27 Self = "core::ops::range::RangeTo<Idx>",
28 note = "you might have meant to use a bounded `Range`"
29 ),
30 on(
31 Self = "core::ops::range::RangeToInclusive<Idx>",
32 note = "you might have meant to use a bounded `RangeInclusive`"
33 ),
34 label = "`{Self}` is not an iterator",
35 message = "`{Self}` is not an iterator"
36)]
37#[doc(notable_trait)]
38#[lang = "iterator"]
39#[rustc_diagnostic_item = "Iterator"]
40#[must_use = "iterators are lazy and do nothing unless consumed"]
41#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
42pub const trait Iterator {
43 /// The type of the elements being iterated over.
44 #[rustc_diagnostic_item = "IteratorItem"]
45 #[stable(feature = "rust1", since = "1.0.0")]
46 type Item;
47
48 /// Advances the iterator and returns the next value.
49 ///
50 /// Returns [`None`] when iteration is finished. Individual iterator
51 /// implementations may choose to resume iteration, and so calling `next()`
52 /// again may or may not eventually start returning [`Some(Item)`] again at some
53 /// point.
54 ///
55 /// [`Some(Item)`]: Some
56 ///
57 /// # Examples
58 ///
59 /// ```
60 /// let a = [1, 2, 3];
61 ///
62 /// let mut iter = a.into_iter();
63 ///
64 /// // A call to next() returns the next value...
65 /// assert_eq!(Some(1), iter.next());
66 /// assert_eq!(Some(2), iter.next());
67 /// assert_eq!(Some(3), iter.next());
68 ///
69 /// // ... and then None once it's over.
70 /// assert_eq!(None, iter.next());
71 ///
72 /// // More calls may or may not return `None`. Here, they always will.
73 /// assert_eq!(None, iter.next());
74 /// assert_eq!(None, iter.next());
75 /// ```
76 #[lang = "next"]
77 #[stable(feature = "rust1", since = "1.0.0")]
78 fn next(&mut self) -> Option<Self::Item>;
79
80 /// Advances the iterator and returns an array containing the next `N` values.
81 ///
82 /// If there are not enough elements to fill the array then `Err` is returned
83 /// containing an iterator over the remaining elements.
84 ///
85 /// # Examples
86 ///
87 /// Basic usage:
88 ///
89 /// ```
90 /// #![feature(iter_next_chunk)]
91 ///
92 /// let mut iter = "lorem".chars();
93 ///
94 /// assert_eq!(iter.next_chunk().unwrap(), ['l', 'o']); // N is inferred as 2
95 /// assert_eq!(iter.next_chunk().unwrap(), ['r', 'e', 'm']); // N is inferred as 3
96 /// assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
97 /// ```
98 ///
99 /// Split a string and get the first three items.
100 ///
101 /// ```
102 /// #![feature(iter_next_chunk)]
103 ///
104 /// let quote = "not all those who wander are lost";
105 /// let [first, second, third] = quote.split_whitespace().next_chunk().unwrap();
106 /// assert_eq!(first, "not");
107 /// assert_eq!(second, "all");
108 /// assert_eq!(third, "those");
109 /// ```
110 #[inline]
111 #[unstable(feature = "iter_next_chunk", issue = "98326")]
112 fn next_chunk<const N: usize>(
113 &mut self,
114 ) -> Result<[Self::Item; N], array::IntoIter<Self::Item, N>>
115 where
116 Self: Sized,
117 {
118 array::iter_next_chunk(self)
119 }
120
121 /// Returns the bounds on the remaining length of the iterator.
122 ///
123 /// Specifically, `size_hint()` returns a tuple where the first element
124 /// is the lower bound, and the second element is the upper bound.
125 ///
126 /// The second half of the tuple that is returned is an <code>[Option]<[usize]></code>.
127 /// A [`None`] here means that either there is no known upper bound, or the
128 /// upper bound is larger than [`usize`].
129 ///
130 /// # Implementation notes
131 ///
132 /// It is not enforced that an iterator implementation yields the declared
133 /// number of elements. A buggy iterator may yield less than the lower bound
134 /// or more than the upper bound of elements.
135 ///
136 /// `size_hint()` is primarily intended to be used for optimizations such as
137 /// reserving space for the elements of the iterator, but must not be
138 /// trusted to e.g., omit bounds checks in unsafe code. An incorrect
139 /// implementation of `size_hint()` should not lead to memory safety
140 /// violations.
141 ///
142 /// That said, the implementation should provide a correct estimation,
143 /// because otherwise it would be a violation of the trait's protocol.
144 ///
145 /// The default implementation returns <code>(0, [None])</code> which is correct for any
146 /// iterator.
147 ///
148 /// # Examples
149 ///
150 /// Basic usage:
151 ///
152 /// ```
153 /// let a = [1, 2, 3];
154 /// let mut iter = a.iter();
155 ///
156 /// assert_eq!((3, Some(3)), iter.size_hint());
157 /// let _ = iter.next();
158 /// assert_eq!((2, Some(2)), iter.size_hint());
159 /// ```
160 ///
161 /// A more complex example:
162 ///
163 /// ```
164 /// // The even numbers in the range of zero to nine.
165 /// let iter = (0..10).filter(|x| x % 2 == 0);
166 ///
167 /// // We might iterate from zero to ten times. Knowing that it's five
168 /// // exactly wouldn't be possible without executing filter().
169 /// assert_eq!((0, Some(10)), iter.size_hint());
170 ///
171 /// // Let's add five more numbers with chain()
172 /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
173 ///
174 /// // now both bounds are increased by five
175 /// assert_eq!((5, Some(15)), iter.size_hint());
176 /// ```
177 ///
178 /// Returning `None` for an upper bound:
179 ///
180 /// ```
181 /// // an infinite iterator has no upper bound
182 /// // and the maximum possible lower bound
183 /// let iter = 0..;
184 ///
185 /// assert_eq!((usize::MAX, None), iter.size_hint());
186 /// ```
187 #[inline]
188 #[stable(feature = "rust1", since = "1.0.0")]
189 fn size_hint(&self) -> (usize, Option<usize>) {
190 (0, None)
191 }
192
193 /// Consumes the iterator, counting the number of iterations and returning it.
194 ///
195 /// This method will call [`next`] repeatedly until [`None`] is encountered,
196 /// returning the number of times it saw [`Some`]. Note that [`next`] has to be
197 /// called at least once even if the iterator does not have any elements.
198 ///
199 /// [`next`]: Iterator::next
200 ///
201 /// # Overflow Behavior
202 ///
203 /// The method does no guarding against overflows, so counting elements of
204 /// an iterator with more than [`usize::MAX`] elements either produces the
205 /// wrong result or panics. If overflow checks are enabled, a panic is
206 /// guaranteed.
207 ///
208 /// # Panics
209 ///
210 /// This function might panic if the iterator has more than [`usize::MAX`]
211 /// elements.
212 ///
213 /// # Examples
214 ///
215 /// ```
216 /// let a = [1, 2, 3];
217 /// assert_eq!(a.iter().count(), 3);
218 ///
219 /// let a = [1, 2, 3, 4, 5];
220 /// assert_eq!(a.iter().count(), 5);
221 /// ```
222 #[inline]
223 #[stable(feature = "rust1", since = "1.0.0")]
224 fn count(self) -> usize
225 where
226 Self: Sized + [const] Destruct,
227 Self::Item: [const] Destruct,
228 {
229 self.fold(
230 0,
231 #[rustc_inherit_overflow_checks]
232 const |accum, _elem| accum + 1,
233 )
234 }
235
236 /// Consumes the iterator, returning the last element.
237 ///
238 /// This method will evaluate the iterator until it returns [`None`]. While
239 /// doing so, it keeps track of the current element. After [`None`] is
240 /// returned, `last()` will then return the last element it saw.
241 ///
242 /// # Panics
243 ///
244 /// This function might panic if the iterator is infinite.
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// let a = [1, 2, 3];
250 /// assert_eq!(a.into_iter().last(), Some(3));
251 ///
252 /// let a = [1, 2, 3, 4, 5];
253 /// assert_eq!(a.into_iter().last(), Some(5));
254 /// ```
255 #[inline]
256 #[stable(feature = "rust1", since = "1.0.0")]
257 fn last(self) -> Option<Self::Item>
258 where
259 Self: Sized + [const] Destruct,
260 Self::Item: [const] Destruct,
261 {
262 #[inline]
263 #[rustc_const_unstable(feature = "const_destruct", issue = "133214")]
264 const fn some<T>(_: Option<T>, x: T) -> Option<T>
265 where
266 T: [const] Destruct,
267 {
268 Some(x)
269 }
270
271 self.fold(None, some)
272 }
273
274 /// Advances the iterator by `n` elements.
275 ///
276 /// This method will eagerly skip `n` elements by calling [`next`] up to `n`
277 /// times until [`None`] is encountered.
278 ///
279 /// `advance_by(n)` will return `Ok(())` if the iterator successfully advances by
280 /// `n` elements, or a `Err(NonZero<usize>)` with value `k` if [`None`] is encountered,
281 /// where `k` is remaining number of steps that could not be advanced because the iterator ran out.
282 /// If `self` is empty and `n` is non-zero, then this returns `Err(n)`.
283 /// Otherwise, `k` is always less than `n`.
284 ///
285 /// Calling `advance_by(0)` can do meaningful work, for example [`Flatten`]
286 /// can advance its outer iterator until it finds an inner iterator that is not empty, which
287 /// then often allows it to return a more accurate `size_hint()` than in its initial state.
288 ///
289 /// [`Flatten`]: crate::iter::Flatten
290 /// [`next`]: Iterator::next
291 ///
292 /// # Examples
293 ///
294 /// ```
295 /// #![feature(iter_advance_by)]
296 ///
297 /// use std::num::NonZero;
298 ///
299 /// let a = [1, 2, 3, 4];
300 /// let mut iter = a.into_iter();
301 ///
302 /// assert_eq!(iter.advance_by(2), Ok(()));
303 /// assert_eq!(iter.next(), Some(3));
304 /// assert_eq!(iter.advance_by(0), Ok(()));
305 /// assert_eq!(iter.advance_by(100), Err(NonZero::new(99).unwrap())); // only `4` was skipped
306 /// ```
307 #[inline]
308 #[unstable(feature = "iter_advance_by", issue = "77404")]
309 #[rustc_non_const_trait_method]
310 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
311 /// Helper trait to specialize `advance_by` via `try_fold` for `Sized` iterators.
312 trait SpecAdvanceBy {
313 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>>;
314 }
315
316 impl<I: Iterator + ?Sized> SpecAdvanceBy for I {
317 default fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
318 for i in 0..n {
319 if self.next().is_none() {
320 // SAFETY: `i` is always less than `n`.
321 return Err(unsafe { NonZero::new_unchecked(n - i) });
322 }
323 }
324 Ok(())
325 }
326 }
327
328 impl<I: Iterator> SpecAdvanceBy for I {
329 fn spec_advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
330 let Some(n) = NonZero::new(n) else {
331 return Ok(());
332 };
333
334 let res = self.try_fold(n, |n, _| NonZero::new(n.get() - 1));
335
336 match res {
337 None => Ok(()),
338 Some(n) => Err(n),
339 }
340 }
341 }
342
343 self.spec_advance_by(n)
344 }
345
346 /// Returns the `n`th element of the iterator.
347 ///
348 /// Like most indexing operations, the count starts from zero, so `nth(0)`
349 /// returns the first value, `nth(1)` the second, and so on.
350 ///
351 /// Note that all preceding elements, as well as the returned element, will be
352 /// consumed from the iterator. That means that the preceding elements will be
353 /// discarded, and also that calling `nth(0)` multiple times on the same iterator
354 /// will return different elements.
355 ///
356 /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
357 /// iterator.
358 ///
359 /// # Examples
360 ///
361 /// Basic usage:
362 ///
363 /// ```
364 /// let a = [1, 2, 3];
365 /// assert_eq!(a.into_iter().nth(1), Some(2));
366 /// ```
367 ///
368 /// Calling `nth()` multiple times doesn't rewind the iterator:
369 ///
370 /// ```
371 /// let a = [1, 2, 3];
372 ///
373 /// let mut iter = a.into_iter();
374 ///
375 /// assert_eq!(iter.nth(1), Some(2));
376 /// assert_eq!(iter.nth(1), None);
377 /// ```
378 ///
379 /// Returning `None` if there are less than `n + 1` elements:
380 ///
381 /// ```
382 /// let a = [1, 2, 3];
383 /// assert_eq!(a.into_iter().nth(10), None);
384 /// ```
385 #[inline]
386 #[stable(feature = "rust1", since = "1.0.0")]
387 #[rustc_non_const_trait_method]
388 fn nth(&mut self, n: usize) -> Option<Self::Item> {
389 self.advance_by(n).ok()?;
390 self.next()
391 }
392
393 /// Creates an iterator starting at the same point, but stepping by
394 /// the given amount at each iteration.
395 ///
396 /// Note 1: The first element of the iterator will always be returned,
397 /// regardless of the step given.
398 ///
399 /// Note 2: The time at which ignored elements are pulled is not fixed.
400 /// `StepBy` behaves like the sequence `self.next()`, `self.nth(step-1)`,
401 /// `self.nth(step-1)`, …, but is also free to behave like the sequence
402 /// `advance_n_and_return_first(&mut self, step)`,
403 /// `advance_n_and_return_first(&mut self, step)`, …
404 /// Which way is used may change for some iterators for performance reasons.
405 /// The second way will advance the iterator earlier and may consume more items.
406 ///
407 /// `advance_n_and_return_first` is the equivalent of:
408 /// ```
409 /// fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
410 /// where
411 /// I: Iterator,
412 /// {
413 /// let next = iter.next();
414 /// if n > 1 {
415 /// iter.nth(n - 2);
416 /// }
417 /// next
418 /// }
419 /// ```
420 ///
421 /// # Panics
422 ///
423 /// The method will panic if the given step is `0`.
424 ///
425 /// # Examples
426 ///
427 /// ```
428 /// let a = [0, 1, 2, 3, 4, 5];
429 /// let mut iter = a.into_iter().step_by(2);
430 ///
431 /// assert_eq!(iter.next(), Some(0));
432 /// assert_eq!(iter.next(), Some(2));
433 /// assert_eq!(iter.next(), Some(4));
434 /// assert_eq!(iter.next(), None);
435 /// ```
436 #[inline]
437 #[stable(feature = "iterator_step_by", since = "1.28.0")]
438 #[rustc_non_const_trait_method]
439 fn step_by(self, step: usize) -> StepBy<Self>
440 where
441 Self: Sized,
442 {
443 StepBy::new(self, step)
444 }
445
446 /// Takes two iterators and creates a new iterator over both in sequence.
447 ///
448 /// `chain()` will return a new iterator which will first iterate over
449 /// values from the first iterator and then over values from the second
450 /// iterator.
451 ///
452 /// In other words, it links two iterators together, in a chain. 🔗
453 ///
454 /// [`once`] is commonly used to adapt a single value into a chain of
455 /// other kinds of iteration.
456 ///
457 /// # Examples
458 ///
459 /// Basic usage:
460 ///
461 /// ```
462 /// let s1 = "abc".chars();
463 /// let s2 = "def".chars();
464 ///
465 /// let mut iter = s1.chain(s2);
466 ///
467 /// assert_eq!(iter.next(), Some('a'));
468 /// assert_eq!(iter.next(), Some('b'));
469 /// assert_eq!(iter.next(), Some('c'));
470 /// assert_eq!(iter.next(), Some('d'));
471 /// assert_eq!(iter.next(), Some('e'));
472 /// assert_eq!(iter.next(), Some('f'));
473 /// assert_eq!(iter.next(), None);
474 /// ```
475 ///
476 /// Since the argument to `chain()` uses [`IntoIterator`], we can pass
477 /// anything that can be converted into an [`Iterator`], not just an
478 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
479 /// [`IntoIterator`], and so can be passed to `chain()` directly:
480 ///
481 /// ```
482 /// let a1 = [1, 2, 3];
483 /// let a2 = [4, 5, 6];
484 ///
485 /// let mut iter = a1.into_iter().chain(a2);
486 ///
487 /// assert_eq!(iter.next(), Some(1));
488 /// assert_eq!(iter.next(), Some(2));
489 /// assert_eq!(iter.next(), Some(3));
490 /// assert_eq!(iter.next(), Some(4));
491 /// assert_eq!(iter.next(), Some(5));
492 /// assert_eq!(iter.next(), Some(6));
493 /// assert_eq!(iter.next(), None);
494 /// ```
495 ///
496 /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`:
497 ///
498 /// ```
499 /// #[cfg(windows)]
500 /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> {
501 /// use std::os::windows::ffi::OsStrExt;
502 /// s.encode_wide().chain(std::iter::once(0)).collect()
503 /// }
504 /// ```
505 ///
506 /// [`once`]: crate::iter::once
507 /// [`OsStr`]: ../../std/ffi/struct.OsStr.html
508 #[inline]
509 #[stable(feature = "rust1", since = "1.0.0")]
510 fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter>
511 where
512 Self: Sized,
513 U: [const] IntoIterator<Item = Self::Item>,
514 {
515 Chain::new(self, other.into_iter())
516 }
517
518 /// 'Zips up' two iterators into a single iterator of pairs.
519 ///
520 /// `zip()` returns a new iterator that will iterate over two other
521 /// iterators, returning a tuple where the first element comes from the
522 /// first iterator, and the second element comes from the second iterator.
523 ///
524 /// In other words, it zips two iterators together, into a single one.
525 ///
526 /// If either iterator returns [`None`], [`next`] from the zipped iterator
527 /// will return [`None`].
528 /// If the zipped iterator has no more elements to return then each further attempt to advance
529 /// it will first try to advance the first iterator at most one time and if it still yielded an item
530 /// try to advance the second iterator at most one time.
531 ///
532 /// To 'undo' the result of zipping up two iterators, see [`unzip`].
533 ///
534 /// [`unzip`]: Iterator::unzip
535 ///
536 /// # Examples
537 ///
538 /// Basic usage:
539 ///
540 /// ```
541 /// let s1 = "abc".chars();
542 /// let s2 = "def".chars();
543 ///
544 /// let mut iter = s1.zip(s2);
545 ///
546 /// assert_eq!(iter.next(), Some(('a', 'd')));
547 /// assert_eq!(iter.next(), Some(('b', 'e')));
548 /// assert_eq!(iter.next(), Some(('c', 'f')));
549 /// assert_eq!(iter.next(), None);
550 /// ```
551 ///
552 /// Since the argument to `zip()` uses [`IntoIterator`], we can pass
553 /// anything that can be converted into an [`Iterator`], not just an
554 /// [`Iterator`] itself. For example, arrays (`[T]`) implement
555 /// [`IntoIterator`], and so can be passed to `zip()` directly:
556 ///
557 /// ```
558 /// let a1 = [1, 2, 3];
559 /// let a2 = [4, 5, 6];
560 ///
561 /// let mut iter = a1.into_iter().zip(a2);
562 ///
563 /// assert_eq!(iter.next(), Some((1, 4)));
564 /// assert_eq!(iter.next(), Some((2, 5)));
565 /// assert_eq!(iter.next(), Some((3, 6)));
566 /// assert_eq!(iter.next(), None);
567 /// ```
568 ///
569 /// `zip()` is often used to zip an infinite iterator to a finite one.
570 /// This works because the finite iterator will eventually return [`None`],
571 /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
572 ///
573 /// ```
574 /// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
575 ///
576 /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
577 ///
578 /// assert_eq!((0, 'f'), enumerate[0]);
579 /// assert_eq!((0, 'f'), zipper[0]);
580 ///
581 /// assert_eq!((1, 'o'), enumerate[1]);
582 /// assert_eq!((1, 'o'), zipper[1]);
583 ///
584 /// assert_eq!((2, 'o'), enumerate[2]);
585 /// assert_eq!((2, 'o'), zipper[2]);
586 /// ```
587 ///
588 /// If both iterators have roughly equivalent syntax, it may be more readable to use [`zip`]:
589 ///
590 /// ```
591 /// use std::iter::zip;
592 ///
593 /// let a = [1, 2, 3];
594 /// let b = [2, 3, 4];
595 ///
596 /// let mut zipped = zip(
597 /// a.into_iter().map(|x| x * 2).skip(1),
598 /// b.into_iter().map(|x| x * 2).skip(1),
599 /// );
600 ///
601 /// assert_eq!(zipped.next(), Some((4, 6)));
602 /// assert_eq!(zipped.next(), Some((6, 8)));
603 /// assert_eq!(zipped.next(), None);
604 /// ```
605 ///
606 /// compared to:
607 ///
608 /// ```
609 /// # let a = [1, 2, 3];
610 /// # let b = [2, 3, 4];
611 /// #
612 /// let mut zipped = a
613 /// .into_iter()
614 /// .map(|x| x * 2)
615 /// .skip(1)
616 /// .zip(b.into_iter().map(|x| x * 2).skip(1));
617 /// #
618 /// # assert_eq!(zipped.next(), Some((4, 6)));
619 /// # assert_eq!(zipped.next(), Some((6, 8)));
620 /// # assert_eq!(zipped.next(), None);
621 /// ```
622 ///
623 /// [`enumerate`]: Iterator::enumerate
624 /// [`next`]: Iterator::next
625 /// [`zip`]: crate::iter::zip
626 #[inline]
627 #[stable(feature = "rust1", since = "1.0.0")]
628 #[rustc_non_const_trait_method]
629 fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter>
630 where
631 Self: Sized,
632 U: IntoIterator,
633 {
634 Zip::new(self, other.into_iter())
635 }
636
637 /// Creates a new iterator which places a copy of `separator` between items
638 /// of the original iterator.
639 ///
640 /// Specifically on fused iterators, it is guaranteed that the new iterator
641 /// places a copy of `separator` between *adjacent* `Some(_)` items. For non-fused iterators,
642 /// it is guaranteed that [`intersperse`] will create a new iterator that places a copy
643 /// of `separator` between `Some(_)` items, particularly just right before the subsequent
644 /// `Some(_)` item.
645 ///
646 /// For example, consider the following non-fused iterator:
647 ///
648 /// ```text
649 /// Some(1) -> Some(2) -> None -> Some(3) -> Some(4) -> ...
650 /// ```
651 ///
652 /// If this non-fused iterator were to be interspersed with `0`,
653 /// then the interspersed iterator will produce:
654 ///
655 /// ```text
656 /// Some(1) -> Some(0) -> Some(2) -> None -> Some(0) -> Some(3) -> Some(0) ->
657 /// Some(4) -> ...
658 /// ```
659 ///
660 /// In case `separator` does not implement [`Clone`] or needs to be
661 /// computed every time, use [`intersperse_with`].
662 ///
663 /// # Examples
664 ///
665 /// Basic usage:
666 ///
667 /// ```
668 /// #![feature(iter_intersperse)]
669 ///
670 /// let mut a = [0, 1, 2].into_iter().intersperse(100);
671 /// assert_eq!(a.next(), Some(0)); // The first element from `a`.
672 /// assert_eq!(a.next(), Some(100)); // The separator.
673 /// assert_eq!(a.next(), Some(1)); // The next element from `a`.
674 /// assert_eq!(a.next(), Some(100)); // The separator.
675 /// assert_eq!(a.next(), Some(2)); // The last element from `a`.
676 /// assert_eq!(a.next(), None); // The iterator is finished.
677 /// ```
678 ///
679 /// `intersperse` can be very useful to join an iterator's items using a common element:
680 /// ```
681 /// #![feature(iter_intersperse)]
682 ///
683 /// let words = ["Hello", "World", "!"];
684 /// let hello: String = words.into_iter().intersperse(" ").collect();
685 /// assert_eq!(hello, "Hello World !");
686 /// ```
687 ///
688 /// [`Clone`]: crate::clone::Clone
689 /// [`intersperse`]: Iterator::intersperse
690 /// [`intersperse_with`]: Iterator::intersperse_with
691 #[inline]
692 #[unstable(feature = "iter_intersperse", issue = "79524")]
693 fn intersperse(self, separator: Self::Item) -> Intersperse<Self>
694 where
695 Self: Sized,
696 Self::Item: Clone,
697 {
698 Intersperse::new(self, separator)
699 }
700
701 /// Creates a new iterator which places an item generated by `separator`
702 /// between items of the original iterator.
703 ///
704 /// Specifically on fused iterators, it is guaranteed that the new iterator
705 /// places an item generated by `separator` between adjacent `Some(_)` items.
706 /// For non-fused iterators, it is guaranteed that [`intersperse_with`] will
707 /// create a new iterator that places an item generated by `separator` between `Some(_)`
708 /// items, particularly just right before the subsequent `Some(_)` item.
709 ///
710 /// For example, consider the following non-fused iterator:
711 ///
712 /// ```text
713 /// Some(1) -> Some(2) -> None -> Some(3) -> Some(4) -> ...
714 /// ```
715 ///
716 /// If this non-fused iterator were to be interspersed with a `separator` closure
717 /// that returns `0` repeatedly, the interspersed iterator will produce:
718 ///
719 /// ```text
720 /// Some(1) -> Some(0) -> Some(2) -> None -> Some(0) -> Some(3) -> Some(0) ->
721 /// Some(4) -> ...
722 /// ```
723 ///
724 /// The `separator` closure will be called exactly once each time an item
725 /// is placed between two adjacent items from the underlying iterator;
726 /// specifically, the closure is not called if the underlying iterator yields
727 /// less than two items and after the last item is yielded.
728 ///
729 /// If the iterator's item implements [`Clone`], it may be easier to use
730 /// [`intersperse`].
731 ///
732 /// # Examples
733 ///
734 /// Basic usage:
735 ///
736 /// ```
737 /// #![feature(iter_intersperse)]
738 ///
739 /// #[derive(PartialEq, Debug)]
740 /// struct NotClone(usize);
741 ///
742 /// let v = [NotClone(0), NotClone(1), NotClone(2)];
743 /// let mut it = v.into_iter().intersperse_with(|| NotClone(99));
744 ///
745 /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`.
746 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
747 /// assert_eq!(it.next(), Some(NotClone(1))); // The next element from `v`.
748 /// assert_eq!(it.next(), Some(NotClone(99))); // The separator.
749 /// assert_eq!(it.next(), Some(NotClone(2))); // The last element from `v`.
750 /// assert_eq!(it.next(), None); // The iterator is finished.
751 /// ```
752 ///
753 /// `intersperse_with` can be used in situations where the separator needs
754 /// to be computed:
755 /// ```
756 /// #![feature(iter_intersperse)]
757 ///
758 /// let src = ["Hello", "to", "all", "people", "!!"].iter().copied();
759 ///
760 /// // The closure mutably borrows its context to generate an item.
761 /// let mut happy_emojis = [" ❤️ ", " 😀 "].into_iter();
762 /// let separator = || happy_emojis.next().unwrap_or(" 🦀 ");
763 ///
764 /// let result = src.intersperse_with(separator).collect::<String>();
765 /// assert_eq!(result, "Hello ❤️ to 😀 all 🦀 people 🦀 !!");
766 /// ```
767 /// [`Clone`]: crate::clone::Clone
768 /// [`intersperse`]: Iterator::intersperse
769 /// [`intersperse_with`]: Iterator::intersperse_with
770 #[inline]
771 #[unstable(feature = "iter_intersperse", issue = "79524")]
772 fn intersperse_with<G>(self, separator: G) -> IntersperseWith<Self, G>
773 where
774 Self: Sized,
775 G: FnMut() -> Self::Item,
776 {
777 IntersperseWith::new(self, separator)
778 }
779
780 /// Takes a closure and creates an iterator which calls that closure on each
781 /// element.
782 ///
783 /// `map()` transforms one iterator into another, by means of its argument:
784 /// something that implements [`FnMut`]. It produces a new iterator which
785 /// calls this closure on each element of the original iterator.
786 ///
787 /// If you are good at thinking in types, you can think of `map()` like this:
788 /// If you have an iterator that gives you elements of some type `A`, and
789 /// you want an iterator of some other type `B`, you can use `map()`,
790 /// passing a closure that takes an `A` and returns a `B`.
791 ///
792 /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
793 /// lazy, it is best used when you're already working with other iterators.
794 /// If you're doing some sort of looping for a side effect, it's considered
795 /// more idiomatic to use [`for`] than `map()`.
796 ///
797 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
798 ///
799 /// # Examples
800 ///
801 /// Basic usage:
802 ///
803 /// ```
804 /// let a = [1, 2, 3];
805 ///
806 /// let mut iter = a.iter().map(|x| 2 * x);
807 ///
808 /// assert_eq!(iter.next(), Some(2));
809 /// assert_eq!(iter.next(), Some(4));
810 /// assert_eq!(iter.next(), Some(6));
811 /// assert_eq!(iter.next(), None);
812 /// ```
813 ///
814 /// If you're doing some sort of side effect, prefer [`for`] to `map()`:
815 ///
816 /// ```
817 /// # #![allow(unused_must_use)]
818 /// // don't do this:
819 /// (0..5).map(|x| println!("{x}"));
820 ///
821 /// // it won't even execute, as it is lazy. Rust will warn you about this.
822 ///
823 /// // Instead, use a for-loop:
824 /// for x in 0..5 {
825 /// println!("{x}");
826 /// }
827 /// ```
828 #[rustc_diagnostic_item = "IteratorMap"]
829 #[inline]
830 #[stable(feature = "rust1", since = "1.0.0")]
831 fn map<B, F>(self, f: F) -> Map<Self, F>
832 where
833 Self: Sized,
834 F: FnMut(Self::Item) -> B,
835 {
836 Map::new(self, f)
837 }
838
839 /// Calls a closure on each element of an iterator.
840 ///
841 /// This is equivalent to using a [`for`] loop on the iterator, although
842 /// `break` and `continue` are not possible from a closure. It's generally
843 /// more idiomatic to use a `for` loop, but `for_each` may be more legible
844 /// when processing items at the end of longer iterator chains. In some
845 /// cases `for_each` may also be faster than a loop, because it will use
846 /// internal iteration on adapters like `Chain`.
847 ///
848 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
849 ///
850 /// # Examples
851 ///
852 /// Basic usage:
853 ///
854 /// ```
855 /// use std::sync::mpsc::channel;
856 ///
857 /// let (tx, rx) = channel();
858 /// (0..5).map(|x| x * 2 + 1)
859 /// .for_each(move |x| tx.send(x).unwrap());
860 ///
861 /// let v: Vec<_> = rx.iter().collect();
862 /// assert_eq!(v, vec![1, 3, 5, 7, 9]);
863 /// ```
864 ///
865 /// For such a small example, a `for` loop may be cleaner, but `for_each`
866 /// might be preferable to keep a functional style with longer iterators:
867 ///
868 /// ```
869 /// (0..5).flat_map(|x| (x * 100)..(x * 110))
870 /// .enumerate()
871 /// .filter(|&(i, x)| (i + x) % 3 == 0)
872 /// .for_each(|(i, x)| println!("{i}:{x}"));
873 /// ```
874 #[inline]
875 #[stable(feature = "iterator_for_each", since = "1.21.0")]
876 #[rustc_non_const_trait_method]
877 fn for_each<F>(self, f: F)
878 where
879 Self: Sized,
880 F: FnMut(Self::Item),
881 {
882 #[inline]
883 fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) {
884 move |(), item| f(item)
885 }
886
887 self.fold((), call(f));
888 }
889
890 /// Creates an iterator which uses a closure to determine if an element
891 /// should be yielded.
892 ///
893 /// Given an element the closure must return `true` or `false`. The returned
894 /// iterator will yield only the elements for which the closure returns
895 /// `true`.
896 ///
897 /// # Examples
898 ///
899 /// Basic usage:
900 ///
901 /// ```
902 /// let a = [0i32, 1, 2];
903 ///
904 /// let mut iter = a.into_iter().filter(|x| x.is_positive());
905 ///
906 /// assert_eq!(iter.next(), Some(1));
907 /// assert_eq!(iter.next(), Some(2));
908 /// assert_eq!(iter.next(), None);
909 /// ```
910 ///
911 /// Because the closure passed to `filter()` takes a reference, and many
912 /// iterators iterate over references, this leads to a possibly confusing
913 /// situation, where the type of the closure is a double reference:
914 ///
915 /// ```
916 /// let s = &[0, 1, 2];
917 ///
918 /// let mut iter = s.iter().filter(|x| **x > 1); // needs two *s!
919 ///
920 /// assert_eq!(iter.next(), Some(&2));
921 /// assert_eq!(iter.next(), None);
922 /// ```
923 ///
924 /// It's common to instead use destructuring on the argument to strip away one:
925 ///
926 /// ```
927 /// let s = &[0, 1, 2];
928 ///
929 /// let mut iter = s.iter().filter(|&x| *x > 1); // both & and *
930 ///
931 /// assert_eq!(iter.next(), Some(&2));
932 /// assert_eq!(iter.next(), None);
933 /// ```
934 ///
935 /// or both:
936 ///
937 /// ```
938 /// let s = &[0, 1, 2];
939 ///
940 /// let mut iter = s.iter().filter(|&&x| x > 1); // two &s
941 ///
942 /// assert_eq!(iter.next(), Some(&2));
943 /// assert_eq!(iter.next(), None);
944 /// ```
945 ///
946 /// of these layers.
947 ///
948 /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`.
949 #[inline]
950 #[stable(feature = "rust1", since = "1.0.0")]
951 #[rustc_diagnostic_item = "iter_filter"]
952 fn filter<P>(self, predicate: P) -> Filter<Self, P>
953 where
954 Self: Sized,
955 P: FnMut(&Self::Item) -> bool,
956 {
957 Filter::new(self, predicate)
958 }
959
960 /// Creates an iterator that both filters and maps.
961 ///
962 /// The returned iterator yields only the `value`s for which the supplied
963 /// closure returns `Some(value)`.
964 ///
965 /// `filter_map` can be used to make chains of [`filter`] and [`map`] more
966 /// concise. The example below shows how a `map().filter().map()` can be
967 /// shortened to a single call to `filter_map`.
968 ///
969 /// [`filter`]: Iterator::filter
970 /// [`map`]: Iterator::map
971 ///
972 /// # Examples
973 ///
974 /// Basic usage:
975 ///
976 /// ```
977 /// let a = ["1", "two", "NaN", "four", "5"];
978 ///
979 /// let mut iter = a.iter().filter_map(|s| s.parse().ok());
980 ///
981 /// assert_eq!(iter.next(), Some(1));
982 /// assert_eq!(iter.next(), Some(5));
983 /// assert_eq!(iter.next(), None);
984 /// ```
985 ///
986 /// Here's the same example, but with [`filter`] and [`map`]:
987 ///
988 /// ```
989 /// let a = ["1", "two", "NaN", "four", "5"];
990 /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
991 /// assert_eq!(iter.next(), Some(1));
992 /// assert_eq!(iter.next(), Some(5));
993 /// assert_eq!(iter.next(), None);
994 /// ```
995 #[inline]
996 #[stable(feature = "rust1", since = "1.0.0")]
997 fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F>
998 where
999 Self: Sized,
1000 F: FnMut(Self::Item) -> Option<B>,
1001 {
1002 FilterMap::new(self, f)
1003 }
1004
1005 /// Creates an iterator which gives the current iteration count as well as
1006 /// the next value.
1007 ///
1008 /// The iterator returned yields pairs `(i, val)`, where `i` is the
1009 /// current index of iteration and `val` is the value returned by the
1010 /// iterator.
1011 ///
1012 /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
1013 /// different sized integer, the [`zip`] function provides similar
1014 /// functionality.
1015 ///
1016 /// # Overflow Behavior
1017 ///
1018 /// The method does no guarding against overflows, so enumerating more than
1019 /// [`usize::MAX`] elements either produces the wrong result or panics. If
1020 /// overflow checks are enabled, a panic is guaranteed.
1021 ///
1022 /// # Panics
1023 ///
1024 /// The returned iterator might panic if the to-be-returned index would
1025 /// overflow a [`usize`].
1026 ///
1027 /// [`zip`]: Iterator::zip
1028 ///
1029 /// # Examples
1030 ///
1031 /// ```
1032 /// let a = ['a', 'b', 'c'];
1033 ///
1034 /// let mut iter = a.into_iter().enumerate();
1035 ///
1036 /// assert_eq!(iter.next(), Some((0, 'a')));
1037 /// assert_eq!(iter.next(), Some((1, 'b')));
1038 /// assert_eq!(iter.next(), Some((2, 'c')));
1039 /// assert_eq!(iter.next(), None);
1040 /// ```
1041 #[inline]
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 #[rustc_diagnostic_item = "enumerate_method"]
1044 fn enumerate(self) -> Enumerate<Self>
1045 where
1046 Self: Sized,
1047 {
1048 Enumerate::new(self)
1049 }
1050
1051 /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods
1052 /// to look at the next element of the iterator without consuming it. See
1053 /// their documentation for more information.
1054 ///
1055 /// Note that the underlying iterator is still advanced when [`peek`] or
1056 /// [`peek_mut`] are called for the first time: In order to retrieve the
1057 /// next element, [`next`] is called on the underlying iterator, hence any
1058 /// side effects (i.e. anything other than fetching the next value) of
1059 /// the [`next`] method will occur.
1060 ///
1061 ///
1062 /// # Examples
1063 ///
1064 /// Basic usage:
1065 ///
1066 /// ```
1067 /// let xs = [1, 2, 3];
1068 ///
1069 /// let mut iter = xs.into_iter().peekable();
1070 ///
1071 /// // peek() lets us see into the future
1072 /// assert_eq!(iter.peek(), Some(&1));
1073 /// assert_eq!(iter.next(), Some(1));
1074 ///
1075 /// assert_eq!(iter.next(), Some(2));
1076 ///
1077 /// // we can peek() multiple times, the iterator won't advance
1078 /// assert_eq!(iter.peek(), Some(&3));
1079 /// assert_eq!(iter.peek(), Some(&3));
1080 ///
1081 /// assert_eq!(iter.next(), Some(3));
1082 ///
1083 /// // after the iterator is finished, so is peek()
1084 /// assert_eq!(iter.peek(), None);
1085 /// assert_eq!(iter.next(), None);
1086 /// ```
1087 ///
1088 /// Using [`peek_mut`] to mutate the next item without advancing the
1089 /// iterator:
1090 ///
1091 /// ```
1092 /// let xs = [1, 2, 3];
1093 ///
1094 /// let mut iter = xs.into_iter().peekable();
1095 ///
1096 /// // `peek_mut()` lets us see into the future
1097 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1098 /// assert_eq!(iter.peek_mut(), Some(&mut 1));
1099 /// assert_eq!(iter.next(), Some(1));
1100 ///
1101 /// if let Some(p) = iter.peek_mut() {
1102 /// assert_eq!(*p, 2);
1103 /// // put a value into the iterator
1104 /// *p = 1000;
1105 /// }
1106 ///
1107 /// // The value reappears as the iterator continues
1108 /// assert_eq!(iter.collect::<Vec<_>>(), vec![1000, 3]);
1109 /// ```
1110 /// [`peek`]: Peekable::peek
1111 /// [`peek_mut`]: Peekable::peek_mut
1112 /// [`next`]: Iterator::next
1113 #[inline]
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 fn peekable(self) -> Peekable<Self>
1116 where
1117 Self: Sized,
1118 {
1119 Peekable::new(self)
1120 }
1121
1122 /// Creates an iterator that [`skip`]s elements based on a predicate.
1123 ///
1124 /// [`skip`]: Iterator::skip
1125 ///
1126 /// `skip_while()` takes a closure as an argument. It will call this
1127 /// closure on each element of the iterator, and ignore elements
1128 /// until it returns `false`.
1129 ///
1130 /// After `false` is returned, `skip_while()`'s job is over, and the
1131 /// rest of the elements are yielded.
1132 ///
1133 /// # Examples
1134 ///
1135 /// Basic usage:
1136 ///
1137 /// ```
1138 /// let a = [-1i32, 0, 1];
1139 ///
1140 /// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
1141 ///
1142 /// assert_eq!(iter.next(), Some(0));
1143 /// assert_eq!(iter.next(), Some(1));
1144 /// assert_eq!(iter.next(), None);
1145 /// ```
1146 ///
1147 /// Because the closure passed to `skip_while()` takes a reference, and many
1148 /// iterators iterate over references, this leads to a possibly confusing
1149 /// situation, where the type of the closure argument is a double reference:
1150 ///
1151 /// ```
1152 /// let s = &[-1, 0, 1];
1153 ///
1154 /// let mut iter = s.iter().skip_while(|x| **x < 0); // need two *s!
1155 ///
1156 /// assert_eq!(iter.next(), Some(&0));
1157 /// assert_eq!(iter.next(), Some(&1));
1158 /// assert_eq!(iter.next(), None);
1159 /// ```
1160 ///
1161 /// Stopping after an initial `false`:
1162 ///
1163 /// ```
1164 /// let a = [-1, 0, 1, -2];
1165 ///
1166 /// let mut iter = a.into_iter().skip_while(|&x| x < 0);
1167 ///
1168 /// assert_eq!(iter.next(), Some(0));
1169 /// assert_eq!(iter.next(), Some(1));
1170 ///
1171 /// // while this would have been false, since we already got a false,
1172 /// // skip_while() isn't used any more
1173 /// assert_eq!(iter.next(), Some(-2));
1174 ///
1175 /// assert_eq!(iter.next(), None);
1176 /// ```
1177 #[inline]
1178 #[doc(alias = "drop_while")]
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
1181 where
1182 Self: Sized,
1183 P: FnMut(&Self::Item) -> bool,
1184 {
1185 SkipWhile::new(self, predicate)
1186 }
1187
1188 /// Creates an iterator that yields elements based on a predicate.
1189 ///
1190 /// `take_while()` takes a closure as an argument. It will call this
1191 /// closure on each element of the iterator, and yield elements
1192 /// while it returns `true`.
1193 ///
1194 /// After `false` is returned, `take_while()`'s job is over, and the
1195 /// rest of the elements are ignored.
1196 ///
1197 /// # Examples
1198 ///
1199 /// Basic usage:
1200 ///
1201 /// ```
1202 /// let a = [-1i32, 0, 1];
1203 ///
1204 /// let mut iter = a.into_iter().take_while(|x| x.is_negative());
1205 ///
1206 /// assert_eq!(iter.next(), Some(-1));
1207 /// assert_eq!(iter.next(), None);
1208 /// ```
1209 ///
1210 /// Because the closure passed to `take_while()` takes a reference, and many
1211 /// iterators iterate over references, this leads to a possibly confusing
1212 /// situation, where the type of the closure is a double reference:
1213 ///
1214 /// ```
1215 /// let s = &[-1, 0, 1];
1216 ///
1217 /// let mut iter = s.iter().take_while(|x| **x < 0); // need two *s!
1218 ///
1219 /// assert_eq!(iter.next(), Some(&-1));
1220 /// assert_eq!(iter.next(), None);
1221 /// ```
1222 ///
1223 /// Stopping after an initial `false`:
1224 ///
1225 /// ```
1226 /// let a = [-1, 0, 1, -2];
1227 ///
1228 /// let mut iter = a.into_iter().take_while(|&x| x < 0);
1229 ///
1230 /// assert_eq!(iter.next(), Some(-1));
1231 ///
1232 /// // We have more elements that are less than zero, but since we already
1233 /// // got a false, take_while() ignores the remaining elements.
1234 /// assert_eq!(iter.next(), None);
1235 /// ```
1236 ///
1237 /// Because `take_while()` needs to look at the value in order to see if it
1238 /// should be included or not, consuming iterators will see that it is
1239 /// removed:
1240 ///
1241 /// ```
1242 /// let a = [1, 2, 3, 4];
1243 /// let mut iter = a.into_iter();
1244 ///
1245 /// let result: Vec<i32> = iter.by_ref().take_while(|&n| n != 3).collect();
1246 ///
1247 /// assert_eq!(result, [1, 2]);
1248 ///
1249 /// let result: Vec<i32> = iter.collect();
1250 ///
1251 /// assert_eq!(result, [4]);
1252 /// ```
1253 ///
1254 /// The `3` is no longer there, because it was consumed in order to see if
1255 /// the iteration should stop, but wasn't placed back into the iterator.
1256 #[inline]
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
1259 where
1260 Self: Sized,
1261 P: FnMut(&Self::Item) -> bool,
1262 {
1263 TakeWhile::new(self, predicate)
1264 }
1265
1266 /// Creates an iterator that both yields elements based on a predicate and maps.
1267 ///
1268 /// `map_while()` takes a closure as an argument. It will call this
1269 /// closure on each element of the iterator, and yield elements
1270 /// while it returns [`Some(_)`][`Some`].
1271 ///
1272 /// # Examples
1273 ///
1274 /// Basic usage:
1275 ///
1276 /// ```
1277 /// let a = [-1i32, 4, 0, 1];
1278 ///
1279 /// let mut iter = a.into_iter().map_while(|x| 16i32.checked_div(x));
1280 ///
1281 /// assert_eq!(iter.next(), Some(-16));
1282 /// assert_eq!(iter.next(), Some(4));
1283 /// assert_eq!(iter.next(), None);
1284 /// ```
1285 ///
1286 /// Here's the same example, but with [`take_while`] and [`map`]:
1287 ///
1288 /// [`take_while`]: Iterator::take_while
1289 /// [`map`]: Iterator::map
1290 ///
1291 /// ```
1292 /// let a = [-1i32, 4, 0, 1];
1293 ///
1294 /// let mut iter = a.into_iter()
1295 /// .map(|x| 16i32.checked_div(x))
1296 /// .take_while(|x| x.is_some())
1297 /// .map(|x| x.unwrap());
1298 ///
1299 /// assert_eq!(iter.next(), Some(-16));
1300 /// assert_eq!(iter.next(), Some(4));
1301 /// assert_eq!(iter.next(), None);
1302 /// ```
1303 ///
1304 /// Stopping after an initial [`None`]:
1305 ///
1306 /// ```
1307 /// let a = [0, 1, 2, -3, 4, 5, -6];
1308 ///
1309 /// let iter = a.into_iter().map_while(|x| u32::try_from(x).ok());
1310 /// let vec: Vec<_> = iter.collect();
1311 ///
1312 /// // We have more elements that could fit in u32 (such as 4, 5), but `map_while` returned `None` for `-3`
1313 /// // (as the `predicate` returned `None`) and `collect` stops at the first `None` encountered.
1314 /// assert_eq!(vec, [0, 1, 2]);
1315 /// ```
1316 ///
1317 /// Because `map_while()` needs to look at the value in order to see if it
1318 /// should be included or not, consuming iterators will see that it is
1319 /// removed:
1320 ///
1321 /// ```
1322 /// let a = [1, 2, -3, 4];
1323 /// let mut iter = a.into_iter();
1324 ///
1325 /// let result: Vec<u32> = iter.by_ref()
1326 /// .map_while(|n| u32::try_from(n).ok())
1327 /// .collect();
1328 ///
1329 /// assert_eq!(result, [1, 2]);
1330 ///
1331 /// let result: Vec<i32> = iter.collect();
1332 ///
1333 /// assert_eq!(result, [4]);
1334 /// ```
1335 ///
1336 /// The `-3` is no longer there, because it was consumed in order to see if
1337 /// the iteration should stop, but wasn't placed back into the iterator.
1338 ///
1339 /// Note that unlike [`take_while`] this iterator is **not** fused.
1340 /// It is also not specified what this iterator returns after the first [`None`] is returned.
1341 /// If you need a fused iterator, use [`fuse`].
1342 ///
1343 /// [`fuse`]: Iterator::fuse
1344 #[inline]
1345 #[stable(feature = "iter_map_while", since = "1.57.0")]
1346 fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
1347 where
1348 Self: Sized,
1349 P: FnMut(Self::Item) -> Option<B>,
1350 {
1351 MapWhile::new(self, predicate)
1352 }
1353
1354 /// Creates an iterator that skips the first `n` elements.
1355 ///
1356 /// `skip(n)` skips elements until `n` elements are skipped or the end of the
1357 /// iterator is reached (whichever happens first). After that, all the remaining
1358 /// elements are yielded. In particular, if the original iterator is too short,
1359 /// then the returned iterator is empty.
1360 ///
1361 /// Rather than overriding this method directly, instead override the `nth` method.
1362 ///
1363 /// # Examples
1364 ///
1365 /// ```
1366 /// let a = [1, 2, 3];
1367 ///
1368 /// let mut iter = a.into_iter().skip(2);
1369 ///
1370 /// assert_eq!(iter.next(), Some(3));
1371 /// assert_eq!(iter.next(), None);
1372 /// ```
1373 #[inline]
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 fn skip(self, n: usize) -> Skip<Self>
1376 where
1377 Self: Sized,
1378 {
1379 Skip::new(self, n)
1380 }
1381
1382 /// Creates an iterator that yields the first `n` elements, or fewer
1383 /// if the underlying iterator ends sooner.
1384 ///
1385 /// `take(n)` yields elements until `n` elements are yielded or the end of
1386 /// the iterator is reached (whichever happens first).
1387 /// The returned iterator is a prefix of length `n` if the original iterator
1388 /// contains at least `n` elements, otherwise it contains all of the
1389 /// (fewer than `n`) elements of the original iterator.
1390 ///
1391 /// # Examples
1392 ///
1393 /// Basic usage:
1394 ///
1395 /// ```
1396 /// let a = [1, 2, 3];
1397 ///
1398 /// let mut iter = a.into_iter().take(2);
1399 ///
1400 /// assert_eq!(iter.next(), Some(1));
1401 /// assert_eq!(iter.next(), Some(2));
1402 /// assert_eq!(iter.next(), None);
1403 /// ```
1404 ///
1405 /// `take()` is often used with an infinite iterator, to make it finite:
1406 ///
1407 /// ```
1408 /// let mut iter = (0..).take(3);
1409 ///
1410 /// assert_eq!(iter.next(), Some(0));
1411 /// assert_eq!(iter.next(), Some(1));
1412 /// assert_eq!(iter.next(), Some(2));
1413 /// assert_eq!(iter.next(), None);
1414 /// ```
1415 ///
1416 /// If less than `n` elements are available,
1417 /// `take` will limit itself to the size of the underlying iterator:
1418 ///
1419 /// ```
1420 /// let v = [1, 2];
1421 /// let mut iter = v.into_iter().take(5);
1422 /// assert_eq!(iter.next(), Some(1));
1423 /// assert_eq!(iter.next(), Some(2));
1424 /// assert_eq!(iter.next(), None);
1425 /// ```
1426 ///
1427 /// Use [`by_ref`] to take from the iterator without consuming it, and then
1428 /// continue using the original iterator:
1429 ///
1430 /// ```
1431 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1432 ///
1433 /// // Take the first two words.
1434 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1435 /// assert_eq!(hello_world, vec!["hello", "world"]);
1436 ///
1437 /// // Collect the rest of the words.
1438 /// // We can only do this because we used `by_ref` earlier.
1439 /// let of_rust: Vec<_> = words.collect();
1440 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1441 /// ```
1442 ///
1443 /// [`by_ref`]: Iterator::by_ref
1444 #[doc(alias = "limit")]
1445 #[inline]
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 fn take(self, n: usize) -> Take<Self>
1448 where
1449 Self: Sized,
1450 {
1451 Take::new(self, n)
1452 }
1453
1454 /// An iterator adapter which, like [`fold`], holds internal state, but
1455 /// unlike [`fold`], produces a new iterator.
1456 ///
1457 /// [`fold`]: Iterator::fold
1458 ///
1459 /// `scan()` takes two arguments: an initial value which seeds the internal
1460 /// state, and a closure with two arguments, the first being a mutable
1461 /// reference to the internal state and the second an iterator element.
1462 /// The closure can assign to the internal state to share state between
1463 /// iterations.
1464 ///
1465 /// On iteration, the closure will be applied to each element of the
1466 /// iterator and the return value from the closure, an [`Option`], is
1467 /// returned by the `next` method. Thus the closure can return
1468 /// `Some(value)` to yield `value`, or `None` to end the iteration.
1469 ///
1470 /// # Examples
1471 ///
1472 /// ```
1473 /// let a = [1, 2, 3, 4];
1474 ///
1475 /// let mut iter = a.into_iter().scan(1, |state, x| {
1476 /// // each iteration, we'll multiply the state by the element ...
1477 /// *state = *state * x;
1478 ///
1479 /// // ... and terminate if the state exceeds 6
1480 /// if *state > 6 {
1481 /// return None;
1482 /// }
1483 /// // ... else yield the negation of the state
1484 /// Some(-*state)
1485 /// });
1486 ///
1487 /// assert_eq!(iter.next(), Some(-1));
1488 /// assert_eq!(iter.next(), Some(-2));
1489 /// assert_eq!(iter.next(), Some(-6));
1490 /// assert_eq!(iter.next(), None);
1491 /// ```
1492 #[inline]
1493 #[stable(feature = "rust1", since = "1.0.0")]
1494 fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
1495 where
1496 Self: Sized,
1497 F: FnMut(&mut St, Self::Item) -> Option<B>,
1498 {
1499 Scan::new(self, initial_state, f)
1500 }
1501
1502 /// Creates an iterator that works like map, but flattens nested structure.
1503 ///
1504 /// The [`map`] adapter is very useful, but only when the closure
1505 /// argument produces values. If it produces an iterator instead, there's
1506 /// an extra layer of indirection. `flat_map()` will remove this extra layer
1507 /// on its own.
1508 ///
1509 /// You can think of `flat_map(f)` as the semantic equivalent
1510 /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
1511 ///
1512 /// Another way of thinking about `flat_map()`: [`map`]'s closure returns
1513 /// one item for each element, and `flat_map()`'s closure returns an
1514 /// iterator for each element.
1515 ///
1516 /// [`map`]: Iterator::map
1517 /// [`flatten`]: Iterator::flatten
1518 ///
1519 /// # Examples
1520 ///
1521 /// ```
1522 /// let words = ["alpha", "beta", "gamma"];
1523 ///
1524 /// // chars() returns an iterator
1525 /// let merged: String = words.iter()
1526 /// .flat_map(|s| s.chars())
1527 /// .collect();
1528 /// assert_eq!(merged, "alphabetagamma");
1529 /// ```
1530 #[inline]
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 #[rustc_non_const_trait_method]
1533 fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
1534 where
1535 Self: Sized,
1536 U: IntoIterator,
1537 F: FnMut(Self::Item) -> U,
1538 {
1539 FlatMap::new(self, f)
1540 }
1541
1542 /// Creates an iterator that flattens nested structure.
1543 ///
1544 /// This is useful when you have an iterator of iterators or an iterator of
1545 /// things that can be turned into iterators and you want to remove one
1546 /// level of indirection.
1547 ///
1548 /// # Examples
1549 ///
1550 /// Basic usage:
1551 ///
1552 /// ```
1553 /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
1554 /// let flattened: Vec<_> = data.into_iter().flatten().collect();
1555 /// assert_eq!(flattened, [1, 2, 3, 4, 5, 6]);
1556 /// ```
1557 ///
1558 /// Mapping and then flattening:
1559 ///
1560 /// ```
1561 /// let words = ["alpha", "beta", "gamma"];
1562 ///
1563 /// // chars() returns an iterator
1564 /// let merged: String = words.iter()
1565 /// .map(|s| s.chars())
1566 /// .flatten()
1567 /// .collect();
1568 /// assert_eq!(merged, "alphabetagamma");
1569 /// ```
1570 ///
1571 /// You can also rewrite this in terms of [`flat_map()`], which is preferable
1572 /// in this case since it conveys intent more clearly:
1573 ///
1574 /// ```
1575 /// let words = ["alpha", "beta", "gamma"];
1576 ///
1577 /// // chars() returns an iterator
1578 /// let merged: String = words.iter()
1579 /// .flat_map(|s| s.chars())
1580 /// .collect();
1581 /// assert_eq!(merged, "alphabetagamma");
1582 /// ```
1583 ///
1584 /// Flattening works on any `IntoIterator` type, including `Option` and `Result`:
1585 ///
1586 /// ```
1587 /// let options = vec![Some(123), Some(321), None, Some(231)];
1588 /// let flattened_options: Vec<_> = options.into_iter().flatten().collect();
1589 /// assert_eq!(flattened_options, [123, 321, 231]);
1590 ///
1591 /// let results = vec![Ok(123), Ok(321), Err(456), Ok(231)];
1592 /// let flattened_results: Vec<_> = results.into_iter().flatten().collect();
1593 /// assert_eq!(flattened_results, [123, 321, 231]);
1594 /// ```
1595 ///
1596 /// Flattening only removes one level of nesting at a time:
1597 ///
1598 /// ```
1599 /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
1600 ///
1601 /// let d2: Vec<_> = d3.into_iter().flatten().collect();
1602 /// assert_eq!(d2, [[1, 2], [3, 4], [5, 6], [7, 8]]);
1603 ///
1604 /// let d1: Vec<_> = d3.into_iter().flatten().flatten().collect();
1605 /// assert_eq!(d1, [1, 2, 3, 4, 5, 6, 7, 8]);
1606 /// ```
1607 ///
1608 /// Here we see that `flatten()` does not perform a "deep" flatten.
1609 /// Instead, only one level of nesting is removed. That is, if you
1610 /// `flatten()` a three-dimensional array, the result will be
1611 /// two-dimensional and not one-dimensional. To get a one-dimensional
1612 /// structure, you have to `flatten()` again.
1613 ///
1614 /// [`flat_map()`]: Iterator::flat_map
1615 #[inline]
1616 #[stable(feature = "iterator_flatten", since = "1.29.0")]
1617 fn flatten(self) -> Flatten<Self>
1618 where
1619 Self: Sized,
1620 Self::Item: IntoIterator,
1621 {
1622 Flatten::new(self)
1623 }
1624
1625 /// Calls the given function `f` for each contiguous window of size `N` over
1626 /// `self` and returns an iterator over the outputs of `f`. Like [`slice::windows()`],
1627 /// the windows during mapping overlap as well.
1628 ///
1629 /// In the following example, the closure is called three times with the
1630 /// arguments `&['a', 'b']`, `&['b', 'c']` and `&['c', 'd']` respectively.
1631 ///
1632 /// ```
1633 /// #![feature(iter_map_windows)]
1634 ///
1635 /// let strings = "abcd".chars()
1636 /// .map_windows(|[x, y]| format!("{}+{}", x, y))
1637 /// .collect::<Vec<String>>();
1638 ///
1639 /// assert_eq!(strings, vec!["a+b", "b+c", "c+d"]);
1640 /// ```
1641 ///
1642 /// Note that the const parameter `N` is usually inferred by the
1643 /// destructured argument in the closure.
1644 ///
1645 /// The returned iterator yields 𝑘 − `N` + 1 items (where 𝑘 is the number of
1646 /// items yielded by `self`). If 𝑘 is less than `N`, this method yields an
1647 /// empty iterator.
1648 ///
1649 /// [`slice::windows()`]: slice::windows
1650 /// [`FusedIterator`]: crate::iter::FusedIterator
1651 ///
1652 /// # Panics
1653 ///
1654 /// Panics if `N` is zero.
1655 ///
1656 /// # Examples
1657 ///
1658 /// Building the sums of neighboring numbers.
1659 ///
1660 /// ```
1661 /// #![feature(iter_map_windows)]
1662 ///
1663 /// let mut it = [1, 3, 8, 1].iter().map_windows(|&[a, b]| a + b);
1664 /// assert_eq!(it.next(), Some(4)); // 1 + 3
1665 /// assert_eq!(it.next(), Some(11)); // 3 + 8
1666 /// assert_eq!(it.next(), Some(9)); // 8 + 1
1667 /// assert_eq!(it.next(), None);
1668 /// ```
1669 ///
1670 /// Since the elements in the following example implement `Copy`, we can
1671 /// just copy the array and get an iterator over the windows.
1672 ///
1673 /// ```
1674 /// #![feature(iter_map_windows)]
1675 ///
1676 /// let mut it = "ferris".chars().map_windows(|w: &[_; 3]| *w);
1677 /// assert_eq!(it.next(), Some(['f', 'e', 'r']));
1678 /// assert_eq!(it.next(), Some(['e', 'r', 'r']));
1679 /// assert_eq!(it.next(), Some(['r', 'r', 'i']));
1680 /// assert_eq!(it.next(), Some(['r', 'i', 's']));
1681 /// assert_eq!(it.next(), None);
1682 /// ```
1683 ///
1684 /// You can also use this function to check the sortedness of an iterator.
1685 /// For the simple case, rather use [`Iterator::is_sorted`].
1686 ///
1687 /// ```
1688 /// #![feature(iter_map_windows)]
1689 ///
1690 /// let mut it = [0.5, 1.0, 3.5, 3.0, 8.5, 8.5, f32::NAN].iter()
1691 /// .map_windows(|[a, b]| a <= b);
1692 ///
1693 /// assert_eq!(it.next(), Some(true)); // 0.5 <= 1.0
1694 /// assert_eq!(it.next(), Some(true)); // 1.0 <= 3.5
1695 /// assert_eq!(it.next(), Some(false)); // 3.5 <= 3.0
1696 /// assert_eq!(it.next(), Some(true)); // 3.0 <= 8.5
1697 /// assert_eq!(it.next(), Some(true)); // 8.5 <= 8.5
1698 /// assert_eq!(it.next(), Some(false)); // 8.5 <= NAN
1699 /// assert_eq!(it.next(), None);
1700 /// ```
1701 ///
1702 /// For non-fused iterators, the window is reset after `None` is yielded.
1703 ///
1704 /// ```
1705 /// #![feature(iter_map_windows)]
1706 ///
1707 /// #[derive(Default)]
1708 /// struct NonFusedIterator {
1709 /// state: i32,
1710 /// }
1711 ///
1712 /// impl Iterator for NonFusedIterator {
1713 /// type Item = i32;
1714 ///
1715 /// fn next(&mut self) -> Option<i32> {
1716 /// let val = self.state;
1717 /// self.state = self.state + 1;
1718 ///
1719 /// // Skip every 5th number
1720 /// if (val + 1) % 5 == 0 {
1721 /// None
1722 /// } else {
1723 /// Some(val)
1724 /// }
1725 /// }
1726 /// }
1727 ///
1728 ///
1729 /// let mut iter = NonFusedIterator::default();
1730 ///
1731 /// assert_eq!(iter.next(), Some(0));
1732 /// assert_eq!(iter.next(), Some(1));
1733 /// assert_eq!(iter.next(), Some(2));
1734 /// assert_eq!(iter.next(), Some(3));
1735 /// assert_eq!(iter.next(), None);
1736 /// assert_eq!(iter.next(), Some(5));
1737 /// assert_eq!(iter.next(), Some(6));
1738 /// assert_eq!(iter.next(), Some(7));
1739 /// assert_eq!(iter.next(), Some(8));
1740 /// assert_eq!(iter.next(), None);
1741 /// assert_eq!(iter.next(), Some(10));
1742 /// assert_eq!(iter.next(), Some(11));
1743 ///
1744 /// let mut iter = NonFusedIterator::default()
1745 /// .map_windows(|arr: &[_; 2]| *arr);
1746 ///
1747 /// assert_eq!(iter.next(), Some([0, 1]));
1748 /// assert_eq!(iter.next(), Some([1, 2]));
1749 /// assert_eq!(iter.next(), Some([2, 3]));
1750 /// assert_eq!(iter.next(), None);
1751 ///
1752 /// assert_eq!(iter.next(), Some([5, 6]));
1753 /// assert_eq!(iter.next(), Some([6, 7]));
1754 /// assert_eq!(iter.next(), Some([7, 8]));
1755 /// assert_eq!(iter.next(), None);
1756 ///
1757 /// assert_eq!(iter.next(), Some([10, 11]));
1758 /// assert_eq!(iter.next(), Some([11, 12]));
1759 /// assert_eq!(iter.next(), Some([12, 13]));
1760 /// assert_eq!(iter.next(), None);
1761 /// ```
1762 #[inline]
1763 #[unstable(feature = "iter_map_windows", issue = "87155")]
1764 fn map_windows<F, R, #[rustc_panics_when_zero] const N: usize>(
1765 self,
1766 f: F,
1767 ) -> MapWindows<Self, F, N>
1768 where
1769 Self: Sized,
1770 F: FnMut(&[Self::Item; N]) -> R,
1771 {
1772 MapWindows::new(self, f)
1773 }
1774
1775 /// Creates an iterator which ends after the first [`None`].
1776 ///
1777 /// After an iterator returns [`None`], future calls may or may not yield
1778 /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
1779 /// [`None`] is given, it will always return [`None`] forever.
1780 ///
1781 /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement
1782 /// the [`FusedIterator`] trait. `fuse()` may therefore behave incorrectly
1783 /// if the [`FusedIterator`] trait is improperly implemented.
1784 ///
1785 /// [`Some(T)`]: Some
1786 /// [`FusedIterator`]: crate::iter::FusedIterator
1787 ///
1788 /// # Examples
1789 ///
1790 /// ```
1791 /// // an iterator which alternates between Some and None
1792 /// struct Alternate {
1793 /// state: i32,
1794 /// }
1795 ///
1796 /// impl Iterator for Alternate {
1797 /// type Item = i32;
1798 ///
1799 /// fn next(&mut self) -> Option<i32> {
1800 /// let val = self.state;
1801 /// self.state = self.state + 1;
1802 ///
1803 /// // if it's even, Some(i32), else None
1804 /// (val % 2 == 0).then_some(val)
1805 /// }
1806 /// }
1807 ///
1808 /// let mut iter = Alternate { state: 0 };
1809 ///
1810 /// // we can see our iterator going back and forth
1811 /// assert_eq!(iter.next(), Some(0));
1812 /// assert_eq!(iter.next(), None);
1813 /// assert_eq!(iter.next(), Some(2));
1814 /// assert_eq!(iter.next(), None);
1815 ///
1816 /// // however, once we fuse it...
1817 /// let mut iter = iter.fuse();
1818 ///
1819 /// assert_eq!(iter.next(), Some(4));
1820 /// assert_eq!(iter.next(), None);
1821 ///
1822 /// // it will always return `None` after the first time.
1823 /// assert_eq!(iter.next(), None);
1824 /// assert_eq!(iter.next(), None);
1825 /// assert_eq!(iter.next(), None);
1826 /// ```
1827 #[inline]
1828 #[stable(feature = "rust1", since = "1.0.0")]
1829 fn fuse(self) -> Fuse<Self>
1830 where
1831 Self: Sized,
1832 {
1833 Fuse::new(self)
1834 }
1835
1836 /// Does something with each element of an iterator, passing the value on.
1837 ///
1838 /// When using iterators, you'll often chain several of them together.
1839 /// While working on such code, you might want to check out what's
1840 /// happening at various parts in the pipeline. To do that, insert
1841 /// a call to `inspect()`.
1842 ///
1843 /// It's more common for `inspect()` to be used as a debugging tool than to
1844 /// exist in your final code, but applications may find it useful in certain
1845 /// situations when errors need to be logged before being discarded.
1846 ///
1847 /// # Examples
1848 ///
1849 /// Basic usage:
1850 ///
1851 /// ```
1852 /// let a = [1, 4, 2, 3];
1853 ///
1854 /// // this iterator sequence is complex.
1855 /// let sum = a.iter()
1856 /// .cloned()
1857 /// .filter(|x| x % 2 == 0)
1858 /// .fold(0, |sum, i| sum + i);
1859 ///
1860 /// println!("{sum}");
1861 ///
1862 /// // let's add some inspect() calls to investigate what's happening
1863 /// let sum = a.iter()
1864 /// .cloned()
1865 /// .inspect(|x| println!("about to filter: {x}"))
1866 /// .filter(|x| x % 2 == 0)
1867 /// .inspect(|x| println!("made it through filter: {x}"))
1868 /// .fold(0, |sum, i| sum + i);
1869 ///
1870 /// println!("{sum}");
1871 /// ```
1872 ///
1873 /// This will print:
1874 ///
1875 /// ```text
1876 /// 6
1877 /// about to filter: 1
1878 /// about to filter: 4
1879 /// made it through filter: 4
1880 /// about to filter: 2
1881 /// made it through filter: 2
1882 /// about to filter: 3
1883 /// 6
1884 /// ```
1885 ///
1886 /// Logging errors before discarding them:
1887 ///
1888 /// ```
1889 /// let lines = ["1", "2", "a"];
1890 ///
1891 /// let sum: i32 = lines
1892 /// .iter()
1893 /// .map(|line| line.parse::<i32>())
1894 /// .inspect(|num| {
1895 /// if let Err(ref e) = *num {
1896 /// println!("Parsing error: {e}");
1897 /// }
1898 /// })
1899 /// .filter_map(Result::ok)
1900 /// .sum();
1901 ///
1902 /// println!("Sum: {sum}");
1903 /// ```
1904 ///
1905 /// This will print:
1906 ///
1907 /// ```text
1908 /// Parsing error: invalid digit found in string
1909 /// Sum: 3
1910 /// ```
1911 #[inline]
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 fn inspect<F>(self, f: F) -> Inspect<Self, F>
1914 where
1915 Self: Sized,
1916 F: FnMut(&Self::Item),
1917 {
1918 Inspect::new(self, f)
1919 }
1920
1921 /// Creates a "by reference" adapter for this instance of `Iterator`.
1922 ///
1923 /// Consuming method calls (direct or indirect calls to `next`)
1924 /// on the "by reference" adapter will consume the original iterator,
1925 /// but ownership-taking methods (those with a `self` parameter)
1926 /// only take ownership of the "by reference" iterator.
1927 ///
1928 /// This is useful for applying ownership-taking methods
1929 /// (such as `take` in the example below)
1930 /// without giving up ownership of the original iterator,
1931 /// so you can use the original iterator afterwards.
1932 ///
1933 /// Uses [`impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; ...}`](Iterator#impl-Iterator-for-%26mut+I).
1934 ///
1935 /// # Examples
1936 ///
1937 /// ```
1938 /// let mut words = ["hello", "world", "of", "Rust"].into_iter();
1939 ///
1940 /// // Take the first two words.
1941 /// let hello_world: Vec<_> = words.by_ref().take(2).collect();
1942 /// assert_eq!(hello_world, vec!["hello", "world"]);
1943 ///
1944 /// // Collect the rest of the words.
1945 /// // We can only do this because we used `by_ref` earlier.
1946 /// let of_rust: Vec<_> = words.collect();
1947 /// assert_eq!(of_rust, vec!["of", "Rust"]);
1948 /// ```
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 fn by_ref(&mut self) -> &mut Self
1951 where
1952 Self: Sized,
1953 {
1954 self
1955 }
1956
1957 /// Transforms an iterator into a collection.
1958 ///
1959 /// `collect()` takes ownership of an iterator and produces whichever
1960 /// collection type you request. The iterator itself carries no knowledge of
1961 /// the eventual container; the target collection is chosen entirely by the
1962 /// type you ask `collect()` to return. This makes `collect()` one of the
1963 /// more powerful methods in the standard library, and it shows up in a wide
1964 /// variety of contexts.
1965 ///
1966 /// The most basic pattern in which `collect()` is used is to turn one
1967 /// collection into another. You take a collection, call [`iter`] on it,
1968 /// do a bunch of transformations, and then `collect()` at the end.
1969 ///
1970 /// `collect()` can also create instances of types that are not typical
1971 /// collections. For example, a [`String`] can be built from [`char`]s,
1972 /// and an iterator of [`Result<T, E>`][`Result`] items can be collected
1973 /// into `Result<Collection<T>, E>`. See the examples below for more.
1974 ///
1975 /// Because `collect()` is so general, it can cause problems with type
1976 /// inference. As such, `collect()` is one of the few times you'll see
1977 /// the syntax affectionately known as the 'turbofish': `::<>`. This
1978 /// helps the inference algorithm understand specifically which collection
1979 /// you're trying to collect into.
1980 ///
1981 /// # Examples
1982 ///
1983 /// Basic usage:
1984 ///
1985 /// ```
1986 /// let a = [1, 2, 3];
1987 ///
1988 /// let doubled: Vec<i32> = a.iter()
1989 /// .map(|x| x * 2)
1990 /// .collect();
1991 ///
1992 /// assert_eq!(vec![2, 4, 6], doubled);
1993 /// ```
1994 ///
1995 /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
1996 /// we could collect into, for example, a [`VecDeque<T>`] instead:
1997 ///
1998 /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
1999 ///
2000 /// ```
2001 /// use std::collections::VecDeque;
2002 ///
2003 /// let a = [1, 2, 3];
2004 ///
2005 /// let doubled: VecDeque<i32> = a.iter().map(|x| x * 2).collect();
2006 ///
2007 /// assert_eq!(2, doubled[0]);
2008 /// assert_eq!(4, doubled[1]);
2009 /// assert_eq!(6, doubled[2]);
2010 /// ```
2011 ///
2012 /// Using the 'turbofish' instead of annotating `doubled`:
2013 ///
2014 /// ```
2015 /// let a = [1, 2, 3];
2016 ///
2017 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
2018 ///
2019 /// assert_eq!(vec![2, 4, 6], doubled);
2020 /// ```
2021 ///
2022 /// Because `collect()` only cares about what you're collecting into, you can
2023 /// still use a partial type hint, `_`, with the turbofish:
2024 ///
2025 /// ```
2026 /// let a = [1, 2, 3];
2027 ///
2028 /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
2029 ///
2030 /// assert_eq!(vec![2, 4, 6], doubled);
2031 /// ```
2032 ///
2033 /// Using `collect()` to make a [`String`]:
2034 ///
2035 /// ```
2036 /// let chars = ['g', 'd', 'k', 'k', 'n'];
2037 ///
2038 /// let hello: String = chars.into_iter()
2039 /// .map(|x| x as u8)
2040 /// .map(|x| (x + 1) as char)
2041 /// .collect();
2042 ///
2043 /// assert_eq!("hello", hello);
2044 /// ```
2045 ///
2046 /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
2047 /// see if any of them failed:
2048 ///
2049 /// ```
2050 /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
2051 ///
2052 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2053 ///
2054 /// // gives us the first error
2055 /// assert_eq!(Err("nope"), result);
2056 ///
2057 /// let results = [Ok(1), Ok(3)];
2058 ///
2059 /// let result: Result<Vec<_>, &str> = results.into_iter().collect();
2060 ///
2061 /// // gives us the list of answers
2062 /// assert_eq!(Ok(vec![1, 3]), result);
2063 /// ```
2064 ///
2065 /// [`iter`]: Iterator::next
2066 /// [`String`]: ../../std/string/struct.String.html
2067 /// [`char`]: type@char
2068 #[inline]
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
2071 #[rustc_diagnostic_item = "iterator_collect_fn"]
2072 #[rustc_non_const_trait_method]
2073 fn collect<B: FromIterator<Self::Item>>(self) -> B
2074 where
2075 Self: Sized,
2076 {
2077 // This is too aggressive to turn on for everything all the time, but PR#137908
2078 // accidentally noticed that some rustc iterators had malformed `size_hint`s,
2079 // so this will help catch such things in debug-assertions-std runners,
2080 // even if users won't actually ever see it.
2081 if cfg!(debug_assertions) {
2082 let hint = self.size_hint();
2083 assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}");
2084 }
2085
2086 FromIterator::from_iter(self)
2087 }
2088
2089 /// Fallibly transforms an iterator into a collection, short circuiting if
2090 /// a failure is encountered.
2091 ///
2092 /// `try_collect()` is a variation of [`collect()`][`collect`] that allows fallible
2093 /// conversions during collection. Its main use case is simplifying conversions from
2094 /// iterators yielding [`Option<T>`][`Option`] into `Option<Collection<T>>`, or similarly for other [`Try`]
2095 /// types (e.g. [`Result`]).
2096 ///
2097 /// Importantly, `try_collect()` doesn't require that the outer [`Try`] type also implements [`FromIterator`];
2098 /// only the inner type produced on `Try::Output` must implement it. Concretely,
2099 /// this means that collecting into `ControlFlow<_, Vec<i32>>` is valid because `Vec<i32>` implements
2100 /// [`FromIterator`], even though [`ControlFlow`] doesn't.
2101 ///
2102 /// Also, if a failure is encountered during `try_collect()`, the iterator is still valid and
2103 /// may continue to be used, in which case it will continue iterating starting after the element that
2104 /// triggered the failure. See the last example below for an example of how this works.
2105 ///
2106 /// # Examples
2107 /// Successfully collecting an iterator of `Option<i32>` into `Option<Vec<i32>>`:
2108 /// ```
2109 /// #![feature(iterator_try_collect)]
2110 ///
2111 /// let u = vec![Some(1), Some(2), Some(3)];
2112 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2113 /// assert_eq!(v, Some(vec![1, 2, 3]));
2114 /// ```
2115 ///
2116 /// Failing to collect in the same way:
2117 /// ```
2118 /// #![feature(iterator_try_collect)]
2119 ///
2120 /// let u = vec![Some(1), Some(2), None, Some(3)];
2121 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2122 /// assert_eq!(v, None);
2123 /// ```
2124 ///
2125 /// A similar example, but with `Result`:
2126 /// ```
2127 /// #![feature(iterator_try_collect)]
2128 ///
2129 /// let u: Vec<Result<i32, ()>> = vec![Ok(1), Ok(2), Ok(3)];
2130 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2131 /// assert_eq!(v, Ok(vec![1, 2, 3]));
2132 ///
2133 /// let u = vec![Ok(1), Ok(2), Err(()), Ok(3)];
2134 /// let v = u.into_iter().try_collect::<Vec<i32>>();
2135 /// assert_eq!(v, Err(()));
2136 /// ```
2137 ///
2138 /// Finally, even [`ControlFlow`] works, despite the fact that it
2139 /// doesn't implement [`FromIterator`]. Note also that the iterator can
2140 /// continue to be used, even if a failure is encountered:
2141 ///
2142 /// ```
2143 /// #![feature(iterator_try_collect)]
2144 ///
2145 /// use core::ops::ControlFlow::{Break, Continue};
2146 ///
2147 /// let u = [Continue(1), Continue(2), Break(3), Continue(4), Continue(5)];
2148 /// let mut it = u.into_iter();
2149 ///
2150 /// let v = it.try_collect::<Vec<_>>();
2151 /// assert_eq!(v, Break(3));
2152 ///
2153 /// let v = it.try_collect::<Vec<_>>();
2154 /// assert_eq!(v, Continue(vec![4, 5]));
2155 /// ```
2156 ///
2157 /// [`collect`]: Iterator::collect
2158 #[inline]
2159 #[unstable(feature = "iterator_try_collect", issue = "94047")]
2160 #[rustc_non_const_trait_method]
2161 fn try_collect<B>(&mut self) -> ChangeOutputType<Self::Item, B>
2162 where
2163 Self: Sized,
2164 Self::Item: Try<Residual: Residual<B>>,
2165 B: FromIterator<<Self::Item as Try>::Output>,
2166 {
2167 try_process(ByRefSized(self), |i| i.collect())
2168 }
2169
2170 /// Collects all the items from an iterator into a collection.
2171 ///
2172 /// This method consumes the iterator and adds all its items to the
2173 /// passed collection. The collection is then returned, so the call chain
2174 /// can be continued.
2175 ///
2176 /// This is useful when you already have a collection and want to add
2177 /// the iterator items to it.
2178 ///
2179 /// This method is a convenience method to call [Extend::extend](trait.Extend.html),
2180 /// but instead of being called on a collection, it's called on an iterator.
2181 ///
2182 /// # Examples
2183 ///
2184 /// Basic usage:
2185 ///
2186 /// ```
2187 /// #![feature(iter_collect_into)]
2188 ///
2189 /// let a = [1, 2, 3];
2190 /// let mut vec: Vec::<i32> = vec![0, 1];
2191 ///
2192 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2193 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2194 ///
2195 /// assert_eq!(vec, vec![0, 1, 2, 4, 6, 10, 20, 30]);
2196 /// ```
2197 ///
2198 /// `Vec` can have a manual set capacity to avoid reallocating it:
2199 ///
2200 /// ```
2201 /// #![feature(iter_collect_into)]
2202 ///
2203 /// let a = [1, 2, 3];
2204 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2205 ///
2206 /// a.iter().map(|x| x * 2).collect_into(&mut vec);
2207 /// a.iter().map(|x| x * 10).collect_into(&mut vec);
2208 ///
2209 /// assert_eq!(6, vec.capacity());
2210 /// assert_eq!(vec, vec![2, 4, 6, 10, 20, 30]);
2211 /// ```
2212 ///
2213 /// The returned mutable reference can be used to continue the call chain:
2214 ///
2215 /// ```
2216 /// #![feature(iter_collect_into)]
2217 ///
2218 /// let a = [1, 2, 3];
2219 /// let mut vec: Vec::<i32> = Vec::with_capacity(6);
2220 ///
2221 /// let count = a.iter().collect_into(&mut vec).iter().count();
2222 ///
2223 /// assert_eq!(count, vec.len());
2224 /// assert_eq!(vec, vec![1, 2, 3]);
2225 ///
2226 /// let count = a.iter().collect_into(&mut vec).iter().count();
2227 ///
2228 /// assert_eq!(count, vec.len());
2229 /// assert_eq!(vec, vec![1, 2, 3, 1, 2, 3]);
2230 /// ```
2231 #[inline]
2232 #[unstable(feature = "iter_collect_into", issue = "94780")]
2233 #[rustc_non_const_trait_method]
2234 fn collect_into<E: Extend<Self::Item>>(self, collection: &mut E) -> &mut E
2235 where
2236 Self: Sized,
2237 {
2238 collection.extend(self);
2239 collection
2240 }
2241
2242 /// Consumes an iterator, creating two collections from it.
2243 ///
2244 /// The predicate passed to `partition()` can return `true`, or `false`.
2245 /// `partition()` returns a pair, all of the elements for which it returned
2246 /// `true`, and all of the elements for which it returned `false`.
2247 ///
2248 /// See also [`is_partitioned()`] and [`partition_in_place()`].
2249 ///
2250 /// [`is_partitioned()`]: Iterator::is_partitioned
2251 /// [`partition_in_place()`]: Iterator::partition_in_place
2252 ///
2253 /// # Examples
2254 ///
2255 /// ```
2256 /// let a = [1, 2, 3];
2257 ///
2258 /// let (even, odd): (Vec<_>, Vec<_>) = a
2259 /// .into_iter()
2260 /// .partition(|n| n % 2 == 0);
2261 ///
2262 /// assert_eq!(even, [2]);
2263 /// assert_eq!(odd, [1, 3]);
2264 /// ```
2265 #[stable(feature = "rust1", since = "1.0.0")]
2266 #[rustc_non_const_trait_method]
2267 fn partition<B, F>(self, f: F) -> (B, B)
2268 where
2269 Self: Sized,
2270 B: Default + Extend<Self::Item>,
2271 F: FnMut(&Self::Item) -> bool,
2272 {
2273 #[inline]
2274 fn extend<'a, T, B: Extend<T>>(
2275 mut f: impl FnMut(&T) -> bool + 'a,
2276 left: &'a mut B,
2277 right: &'a mut B,
2278 ) -> impl FnMut((), T) + 'a {
2279 move |(), x| {
2280 if f(&x) {
2281 left.extend_one(x);
2282 } else {
2283 right.extend_one(x);
2284 }
2285 }
2286 }
2287
2288 let mut left: B = Default::default();
2289 let mut right: B = Default::default();
2290
2291 self.fold((), extend(f, &mut left, &mut right));
2292
2293 (left, right)
2294 }
2295
2296 /// Reorders the elements of this iterator *in-place* according to the given predicate,
2297 /// such that all those that return `true` precede all those that return `false`.
2298 /// Returns the number of `true` elements found.
2299 ///
2300 /// The relative order of partitioned items is not maintained.
2301 ///
2302 /// # Current implementation
2303 ///
2304 /// The current algorithm tries to find the first element for which the predicate evaluates
2305 /// to false and the last element for which it evaluates to true, and repeatedly swaps them.
2306 ///
2307 /// Time complexity: *O*(*n*)
2308 ///
2309 /// See also [`is_partitioned()`] and [`partition()`].
2310 ///
2311 /// [`is_partitioned()`]: Iterator::is_partitioned
2312 /// [`partition()`]: Iterator::partition
2313 ///
2314 /// # Examples
2315 ///
2316 /// ```
2317 /// #![feature(iter_partition_in_place)]
2318 ///
2319 /// let mut a = [1, 2, 3, 4, 5, 6, 7];
2320 ///
2321 /// // Partition in-place between evens and odds
2322 /// let i = a.iter_mut().partition_in_place(|n| n % 2 == 0);
2323 ///
2324 /// assert_eq!(i, 3);
2325 /// assert!(a[..i].iter().all(|n| n % 2 == 0)); // evens
2326 /// assert!(a[i..].iter().all(|n| n % 2 == 1)); // odds
2327 /// ```
2328 #[unstable(feature = "iter_partition_in_place", issue = "62543")]
2329 #[rustc_non_const_trait_method]
2330 fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize
2331 where
2332 Self: Sized + DoubleEndedIterator<Item = &'a mut T>,
2333 P: FnMut(&T) -> bool,
2334 {
2335 // FIXME: should we worry about the count overflowing? The only way to have more than
2336 // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition...
2337
2338 // These closure "factory" functions exist to avoid genericity in `Self`.
2339
2340 #[inline]
2341 fn is_false<'a, T>(
2342 predicate: &'a mut impl FnMut(&T) -> bool,
2343 true_count: &'a mut usize,
2344 ) -> impl FnMut(&&mut T) -> bool + 'a {
2345 move |x| {
2346 let p = predicate(&**x);
2347 *true_count += p as usize;
2348 !p
2349 }
2350 }
2351
2352 #[inline]
2353 fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ {
2354 move |x| predicate(&**x)
2355 }
2356
2357 // Repeatedly find the first `false` and swap it with the last `true`.
2358 let mut true_count = 0;
2359 while let Some(head) = self.find(is_false(predicate, &mut true_count)) {
2360 if let Some(tail) = self.rfind(is_true(predicate)) {
2361 crate::mem::swap(head, tail);
2362 true_count += 1;
2363 } else {
2364 break;
2365 }
2366 }
2367 true_count
2368 }
2369
2370 /// Checks if the elements of this iterator are partitioned according to the given predicate,
2371 /// such that all those that return `true` precede all those that return `false`.
2372 ///
2373 /// See also [`partition()`] and [`partition_in_place()`].
2374 ///
2375 /// [`partition()`]: Iterator::partition
2376 /// [`partition_in_place()`]: Iterator::partition_in_place
2377 ///
2378 /// # Examples
2379 ///
2380 /// ```
2381 /// #![feature(iter_is_partitioned)]
2382 ///
2383 /// assert!("Iterator".chars().is_partitioned(char::is_uppercase));
2384 /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase));
2385 /// ```
2386 #[unstable(feature = "iter_is_partitioned", issue = "62544")]
2387 #[rustc_non_const_trait_method]
2388 fn is_partitioned<P>(mut self, mut predicate: P) -> bool
2389 where
2390 Self: Sized,
2391 P: FnMut(Self::Item) -> bool,
2392 {
2393 // Either all items test `true`, or the first clause stops at `false`
2394 // and we check that there are no more `true` items after that.
2395 self.all(&mut predicate) || !self.any(predicate)
2396 }
2397
2398 /// An iterator method that applies a function as long as it returns
2399 /// successfully, producing a single, final value.
2400 ///
2401 /// `try_fold()` takes two arguments: an initial value, and a closure with
2402 /// two arguments: an 'accumulator', and an element. The closure either
2403 /// returns successfully, with the value that the accumulator should have
2404 /// for the next iteration, or it returns failure, with an error value that
2405 /// is propagated back to the caller immediately (short-circuiting).
2406 ///
2407 /// The initial value is the value the accumulator will have on the first
2408 /// call. If applying the closure succeeded against every element of the
2409 /// iterator, `try_fold()` returns the final accumulator as success.
2410 ///
2411 /// Folding is useful whenever you have a collection of something, and want
2412 /// to produce a single value from it.
2413 ///
2414 /// # Note to Implementors
2415 ///
2416 /// Several of the other (forward) methods have default implementations in
2417 /// terms of this one, so try to implement this explicitly if it can
2418 /// do something better than the default `for` loop implementation.
2419 ///
2420 /// In particular, try to have this call `try_fold()` on the internal parts
2421 /// from which this iterator is composed. If multiple calls are needed,
2422 /// the `?` operator may be convenient for chaining the accumulator value
2423 /// along, but beware any invariants that need to be upheld before those
2424 /// early returns. This is a `&mut self` method, so iteration needs to be
2425 /// resumable after hitting an error here.
2426 ///
2427 /// # Examples
2428 ///
2429 /// Basic usage:
2430 ///
2431 /// ```
2432 /// let a = [1, 2, 3];
2433 ///
2434 /// // the checked sum of all of the elements of the array
2435 /// let sum = a.into_iter().try_fold(0i8, |acc, x| acc.checked_add(x));
2436 ///
2437 /// assert_eq!(sum, Some(6));
2438 /// ```
2439 ///
2440 /// Short-circuiting:
2441 ///
2442 /// ```
2443 /// let a = [10, 20, 30, 100, 40, 50];
2444 /// let mut iter = a.into_iter();
2445 ///
2446 /// // This sum overflows when adding the 100 element
2447 /// let sum = iter.try_fold(0i8, |acc, x| acc.checked_add(x));
2448 /// assert_eq!(sum, None);
2449 ///
2450 /// // Because it short-circuited, the remaining elements are still
2451 /// // available through the iterator.
2452 /// assert_eq!(iter.len(), 2);
2453 /// assert_eq!(iter.next(), Some(40));
2454 /// ```
2455 ///
2456 /// While you cannot `break` from a closure, the [`ControlFlow`] type allows
2457 /// a similar idea:
2458 ///
2459 /// ```
2460 /// use std::ops::ControlFlow;
2461 ///
2462 /// let triangular = (1..30).try_fold(0_i8, |prev, x| {
2463 /// if let Some(next) = prev.checked_add(x) {
2464 /// ControlFlow::Continue(next)
2465 /// } else {
2466 /// ControlFlow::Break(prev)
2467 /// }
2468 /// });
2469 /// assert_eq!(triangular, ControlFlow::Break(120));
2470 ///
2471 /// let triangular = (1..30).try_fold(0_u64, |prev, x| {
2472 /// if let Some(next) = prev.checked_add(x) {
2473 /// ControlFlow::Continue(next)
2474 /// } else {
2475 /// ControlFlow::Break(prev)
2476 /// }
2477 /// });
2478 /// assert_eq!(triangular, ControlFlow::Continue(435));
2479 /// ```
2480 #[inline]
2481 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2482 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
2483 where
2484 Self: Sized,
2485 F: [const] FnMut(B, Self::Item) -> R + [const] Destruct,
2486 R: [const] Try<Output = B>,
2487 {
2488 let mut accum = init;
2489 while let Some(x) = self.next() {
2490 accum = f(accum, x)?;
2491 }
2492 try { accum }
2493 }
2494
2495 /// An iterator method that applies a fallible function to each item in the
2496 /// iterator, stopping at the first error and returning that error.
2497 ///
2498 /// This can also be thought of as the fallible form of [`for_each()`]
2499 /// or as the stateless version of [`try_fold()`].
2500 ///
2501 /// [`for_each()`]: Iterator::for_each
2502 /// [`try_fold()`]: Iterator::try_fold
2503 ///
2504 /// # Examples
2505 ///
2506 /// ```
2507 /// use std::fs::rename;
2508 /// use std::io::{stdout, Write};
2509 /// use std::path::Path;
2510 ///
2511 /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
2512 ///
2513 /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
2514 /// assert!(res.is_ok());
2515 ///
2516 /// let mut it = data.iter().cloned();
2517 /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
2518 /// assert!(res.is_err());
2519 /// // It short-circuited, so the remaining items are still in the iterator:
2520 /// assert_eq!(it.next(), Some("stale_bread.json"));
2521 /// ```
2522 ///
2523 /// The [`ControlFlow`] type can be used with this method for the situations
2524 /// in which you'd use `break` and `continue` in a normal loop:
2525 ///
2526 /// ```
2527 /// use std::ops::ControlFlow;
2528 ///
2529 /// let r = (2..100).try_for_each(|x| {
2530 /// if 323 % x == 0 {
2531 /// return ControlFlow::Break(x)
2532 /// }
2533 ///
2534 /// ControlFlow::Continue(())
2535 /// });
2536 /// assert_eq!(r, ControlFlow::Break(17));
2537 /// ```
2538 #[inline]
2539 #[stable(feature = "iterator_try_fold", since = "1.27.0")]
2540 #[rustc_non_const_trait_method]
2541 fn try_for_each<F, R>(&mut self, f: F) -> R
2542 where
2543 Self: Sized,
2544 F: FnMut(Self::Item) -> R,
2545 R: Try<Output = ()>,
2546 {
2547 #[inline]
2548 fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R {
2549 move |(), x| f(x)
2550 }
2551
2552 self.try_fold((), call(f))
2553 }
2554
2555 /// Folds every element into an accumulator by applying an operation,
2556 /// returning the final result.
2557 ///
2558 /// `fold()` takes two arguments: an initial value, and a closure with two
2559 /// arguments: an 'accumulator', and an element. The closure returns the value that
2560 /// the accumulator should have for the next iteration.
2561 ///
2562 /// The initial value is the value the accumulator will have on the first
2563 /// call.
2564 ///
2565 /// After applying this closure to every element of the iterator, `fold()`
2566 /// returns the accumulator.
2567 ///
2568 /// This operation is sometimes called 'reduce' or 'inject'.
2569 ///
2570 /// Folding is useful whenever you have a collection of something, and want
2571 /// to produce a single value from it.
2572 ///
2573 /// Note: `fold()`, and similar methods that traverse the entire iterator,
2574 /// might not terminate for infinite iterators, even on traits for which a
2575 /// result is determinable in finite time.
2576 ///
2577 /// Note: [`reduce()`] can be used to use the first element as the initial
2578 /// value, if the accumulator type and item type is the same.
2579 ///
2580 /// Note: `fold()` combines elements in a *left-associative* fashion. For associative
2581 /// operators like `+`, the order the elements are combined in is not important, but for non-associative
2582 /// operators like `-` the order will affect the final result.
2583 /// For a *right-associative* version of `fold()`, see [`DoubleEndedIterator::rfold()`].
2584 ///
2585 /// # Note to Implementors
2586 ///
2587 /// Several of the other (forward) methods have default implementations in
2588 /// terms of this one, so try to implement this explicitly if it can
2589 /// do something better than the default `for` loop implementation.
2590 ///
2591 /// In particular, try to have this call `fold()` on the internal parts
2592 /// from which this iterator is composed.
2593 ///
2594 /// # Examples
2595 ///
2596 /// Basic usage:
2597 ///
2598 /// ```
2599 /// let a = [1, 2, 3];
2600 ///
2601 /// // the sum of all of the elements of the array
2602 /// let sum = a.iter().fold(0, |acc, x| acc + x);
2603 ///
2604 /// assert_eq!(sum, 6);
2605 /// ```
2606 ///
2607 /// Let's walk through each step of the iteration here:
2608 ///
2609 /// | element | acc | x | result |
2610 /// |---------|-----|---|--------|
2611 /// | | 0 | | |
2612 /// | 1 | 0 | 1 | 1 |
2613 /// | 2 | 1 | 2 | 3 |
2614 /// | 3 | 3 | 3 | 6 |
2615 ///
2616 /// And so, our final result, `6`.
2617 ///
2618 /// This example demonstrates the left-associative nature of `fold()`:
2619 /// it builds a string, starting with an initial value
2620 /// and continuing with each element from the front until the back:
2621 ///
2622 /// ```
2623 /// let numbers = [1, 2, 3, 4, 5];
2624 ///
2625 /// let zero = "0".to_string();
2626 ///
2627 /// let result = numbers.iter().fold(zero, |acc, &x| {
2628 /// format!("({acc} + {x})")
2629 /// });
2630 ///
2631 /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");
2632 /// ```
2633 /// It's common for people who haven't used iterators a lot to
2634 /// use a `for` loop with a list of things to build up a result. Those
2635 /// can be turned into `fold()`s:
2636 ///
2637 /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
2638 ///
2639 /// ```
2640 /// let numbers = [1, 2, 3, 4, 5];
2641 ///
2642 /// let mut result = 0;
2643 ///
2644 /// // for loop:
2645 /// for i in &numbers {
2646 /// result = result + i;
2647 /// }
2648 ///
2649 /// // fold:
2650 /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
2651 ///
2652 /// // they're the same
2653 /// assert_eq!(result, result2);
2654 /// ```
2655 ///
2656 /// [`reduce()`]: Iterator::reduce
2657 #[doc(alias = "inject", alias = "foldl")]
2658 #[inline]
2659 #[stable(feature = "rust1", since = "1.0.0")]
2660 fn fold<B, F>(mut self, init: B, mut f: F) -> B
2661 where
2662 Self: Sized + [const] Destruct,
2663 F: [const] FnMut(B, Self::Item) -> B + [const] Destruct,
2664 {
2665 let mut accum = init;
2666 while let Some(x) = self.next() {
2667 accum = f(accum, x);
2668 }
2669 accum
2670 }
2671
2672 /// Reduces the elements to a single one, by repeatedly applying a reducing
2673 /// operation.
2674 ///
2675 /// If the iterator is empty, returns [`None`]; otherwise, returns the
2676 /// result of the reduction.
2677 ///
2678 /// The reducing function is a closure with two arguments: an 'accumulator', and an element.
2679 /// For iterators with at least one element, this is the same as [`fold()`]
2680 /// with the first element of the iterator as the initial accumulator value, folding
2681 /// every subsequent element into it.
2682 ///
2683 /// [`fold()`]: Iterator::fold
2684 ///
2685 /// # Example
2686 ///
2687 /// ```
2688 /// let reduced: i32 = (1..10).reduce(|acc, e| acc + e).unwrap_or(0);
2689 /// assert_eq!(reduced, 45);
2690 ///
2691 /// // Which is equivalent to doing it with `fold`:
2692 /// let folded: i32 = (1..10).fold(0, |acc, e| acc + e);
2693 /// assert_eq!(reduced, folded);
2694 /// ```
2695 #[inline]
2696 #[stable(feature = "iterator_fold_self", since = "1.51.0")]
2697 fn reduce<F>(mut self, f: F) -> Option<Self::Item>
2698 where
2699 Self: Sized + [const] Destruct,
2700 F: [const] FnMut(Self::Item, Self::Item) -> Self::Item + [const] Destruct,
2701 {
2702 let first = self.next()?;
2703 Some(self.fold(first, f))
2704 }
2705
2706 /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the
2707 /// closure returns a failure, the failure is propagated back to the caller immediately.
2708 ///
2709 /// The return type of this method depends on the return type of the closure. If the closure
2710 /// returns `Result<Self::Item, E>`, then this function will return `Result<Option<Self::Item>,
2711 /// E>`. If the closure returns `Option<Self::Item>`, then this function will return
2712 /// `Option<Option<Self::Item>>`.
2713 ///
2714 /// When called on an empty iterator, this function will return either `Some(None)` or
2715 /// `Ok(None)` depending on the type of the provided closure.
2716 ///
2717 /// For iterators with at least one element, this is essentially the same as calling
2718 /// [`try_fold()`] with the first element of the iterator as the initial accumulator value.
2719 ///
2720 /// [`try_fold()`]: Iterator::try_fold
2721 ///
2722 /// # Examples
2723 ///
2724 /// Safely calculate the sum of a series of numbers:
2725 ///
2726 /// ```
2727 /// #![feature(iterator_try_reduce)]
2728 ///
2729 /// let numbers: Vec<usize> = vec![10, 20, 5, 23, 0];
2730 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2731 /// assert_eq!(sum, Some(Some(58)));
2732 /// ```
2733 ///
2734 /// Determine when a reduction short circuited:
2735 ///
2736 /// ```
2737 /// #![feature(iterator_try_reduce)]
2738 ///
2739 /// let numbers = vec![1, 2, 3, usize::MAX, 4, 5];
2740 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2741 /// assert_eq!(sum, None);
2742 /// ```
2743 ///
2744 /// Determine when a reduction was not performed because there are no elements:
2745 ///
2746 /// ```
2747 /// #![feature(iterator_try_reduce)]
2748 ///
2749 /// let numbers: Vec<usize> = Vec::new();
2750 /// let sum = numbers.into_iter().try_reduce(|x, y| x.checked_add(y));
2751 /// assert_eq!(sum, Some(None));
2752 /// ```
2753 ///
2754 /// Use a [`Result`] instead of an [`Option`]:
2755 ///
2756 /// ```
2757 /// #![feature(iterator_try_reduce)]
2758 ///
2759 /// let numbers = vec!["1", "2", "3", "4", "5"];
2760 /// let max: Result<Option<_>, <usize as std::str::FromStr>::Err> =
2761 /// numbers.into_iter().try_reduce(|x, y| {
2762 /// if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) }
2763 /// });
2764 /// assert_eq!(max, Ok(Some("5")));
2765 /// ```
2766 #[inline]
2767 #[unstable(feature = "iterator_try_reduce", issue = "87053")]
2768 fn try_reduce<R>(
2769 &mut self,
2770 f: impl [const] FnMut(Self::Item, Self::Item) -> R + [const] Destruct,
2771 ) -> ChangeOutputType<R, Option<R::Output>>
2772 where
2773 Self: Sized,
2774 R: [const] Try<Output = Self::Item, Residual: [const] Residual<Option<Self::Item>>>,
2775 {
2776 let first = match self.next() {
2777 Some(i) => i,
2778 None => return Try::from_output(None),
2779 };
2780
2781 match self.try_fold(first, f).branch() {
2782 ControlFlow::Break(r) => FromResidual::from_residual(r),
2783 ControlFlow::Continue(i) => Try::from_output(Some(i)),
2784 }
2785 }
2786
2787 /// Tests if every element of the iterator matches a predicate.
2788 ///
2789 /// `all()` takes a closure that returns `true` or `false`. It applies
2790 /// this closure to each element of the iterator, and if they all return
2791 /// `true`, then so does `all()`. If any of them return `false`, it
2792 /// returns `false`.
2793 ///
2794 /// `all()` is short-circuiting; in other words, it will stop processing
2795 /// as soon as it finds a `false`, given that no matter what else happens,
2796 /// the result will also be `false`.
2797 ///
2798 /// An empty iterator returns `true`.
2799 ///
2800 /// # Examples
2801 ///
2802 /// Basic usage:
2803 ///
2804 /// ```
2805 /// let a = [1, 2, 3];
2806 ///
2807 /// assert!(a.into_iter().all(|x| x > 0));
2808 ///
2809 /// assert!(!a.into_iter().all(|x| x > 2));
2810 /// ```
2811 ///
2812 /// Stopping at the first `false`:
2813 ///
2814 /// ```
2815 /// let a = [1, 2, 3];
2816 ///
2817 /// let mut iter = a.into_iter();
2818 ///
2819 /// assert!(!iter.all(|x| x != 2));
2820 ///
2821 /// // we can still use `iter`, as there are more elements.
2822 /// assert_eq!(iter.next(), Some(3));
2823 /// ```
2824 #[inline]
2825 #[stable(feature = "rust1", since = "1.0.0")]
2826 #[rustc_non_const_trait_method]
2827 fn all<F>(&mut self, f: F) -> bool
2828 where
2829 Self: Sized,
2830 F: FnMut(Self::Item) -> bool,
2831 {
2832 #[inline]
2833 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2834 move |(), x| {
2835 if f(x) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
2836 }
2837 }
2838 self.try_fold((), check(f)) == ControlFlow::Continue(())
2839 }
2840
2841 /// Tests if any element of the iterator matches a predicate.
2842 ///
2843 /// `any()` takes a closure that returns `true` or `false`. It applies
2844 /// this closure to each element of the iterator, and if any of them return
2845 /// `true`, then so does `any()`. If they all return `false`, it
2846 /// returns `false`.
2847 ///
2848 /// `any()` is short-circuiting; in other words, it will stop processing
2849 /// as soon as it finds a `true`, given that no matter what else happens,
2850 /// the result will also be `true`.
2851 ///
2852 /// An empty iterator returns `false`.
2853 ///
2854 /// # Examples
2855 ///
2856 /// Basic usage:
2857 ///
2858 /// ```
2859 /// let a = [1, 2, 3];
2860 ///
2861 /// assert!(a.into_iter().any(|x| x > 0));
2862 ///
2863 /// assert!(!a.into_iter().any(|x| x > 5));
2864 /// ```
2865 ///
2866 /// Stopping at the first `true`:
2867 ///
2868 /// ```
2869 /// let a = [1, 2, 3];
2870 ///
2871 /// let mut iter = a.into_iter();
2872 ///
2873 /// assert!(iter.any(|x| x != 2));
2874 ///
2875 /// // we can still use `iter`, as there are more elements.
2876 /// assert_eq!(iter.next(), Some(2));
2877 /// ```
2878 #[inline]
2879 #[stable(feature = "rust1", since = "1.0.0")]
2880 #[rustc_non_const_trait_method]
2881 fn any<F>(&mut self, f: F) -> bool
2882 where
2883 Self: Sized,
2884 F: FnMut(Self::Item) -> bool,
2885 {
2886 #[inline]
2887 fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> {
2888 move |(), x| {
2889 if f(x) { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
2890 }
2891 }
2892
2893 self.try_fold((), check(f)) == ControlFlow::Break(())
2894 }
2895
2896 /// Searches for an element of an iterator that satisfies a predicate.
2897 ///
2898 /// `find()` takes a closure that returns `true` or `false`. It applies
2899 /// this closure to each element of the iterator, and if any of them return
2900 /// `true`, then `find()` returns [`Some(element)`]. If they all return
2901 /// `false`, it returns [`None`].
2902 ///
2903 /// `find()` is short-circuiting; in other words, it will stop processing
2904 /// as soon as the closure returns `true`.
2905 ///
2906 /// Because `find()` takes a reference, and many iterators iterate over
2907 /// references, this leads to a possibly confusing situation where the
2908 /// argument is a double reference. You can see this effect in the
2909 /// examples below, with `&&x`.
2910 ///
2911 /// If you need the index of the element, see [`position()`].
2912 ///
2913 /// [`Some(element)`]: Some
2914 /// [`position()`]: Iterator::position
2915 ///
2916 /// # Examples
2917 ///
2918 /// Basic usage:
2919 ///
2920 /// ```
2921 /// let a = [1, 2, 3];
2922 ///
2923 /// assert_eq!(a.into_iter().find(|&x| x == 2), Some(2));
2924 /// assert_eq!(a.into_iter().find(|&x| x == 5), None);
2925 /// ```
2926 ///
2927 /// Iterating over references:
2928 ///
2929 /// ```
2930 /// let a = [1, 2, 3];
2931 ///
2932 /// // `iter()` yields references i.e. `&i32` and `find()` takes a
2933 /// // reference to each element.
2934 /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
2935 /// assert_eq!(a.iter().find(|&&x| x == 5), None);
2936 /// ```
2937 ///
2938 /// Stopping at the first `true`:
2939 ///
2940 /// ```
2941 /// let a = [1, 2, 3];
2942 ///
2943 /// let mut iter = a.into_iter();
2944 ///
2945 /// assert_eq!(iter.find(|&x| x == 2), Some(2));
2946 ///
2947 /// // we can still use `iter`, as there are more elements.
2948 /// assert_eq!(iter.next(), Some(3));
2949 /// ```
2950 ///
2951 /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`.
2952 #[inline]
2953 #[stable(feature = "rust1", since = "1.0.0")]
2954 #[rustc_non_const_trait_method]
2955 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
2956 where
2957 Self: Sized,
2958 P: FnMut(&Self::Item) -> bool,
2959 {
2960 #[inline]
2961 fn check<T>(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow<T> {
2962 move |(), x| {
2963 if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::Continue(()) }
2964 }
2965 }
2966
2967 self.try_fold((), check(predicate)).break_value()
2968 }
2969
2970 /// Applies function to the elements of iterator and returns
2971 /// the first non-none result.
2972 ///
2973 /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
2974 ///
2975 /// # Examples
2976 ///
2977 /// ```
2978 /// let a = ["lol", "NaN", "2", "5"];
2979 ///
2980 /// let first_number = a.iter().find_map(|s| s.parse().ok());
2981 ///
2982 /// assert_eq!(first_number, Some(2));
2983 /// ```
2984 #[inline]
2985 #[stable(feature = "iterator_find_map", since = "1.30.0")]
2986 #[rustc_non_const_trait_method]
2987 fn find_map<B, F>(&mut self, f: F) -> Option<B>
2988 where
2989 Self: Sized,
2990 F: FnMut(Self::Item) -> Option<B>,
2991 {
2992 #[inline]
2993 fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> ControlFlow<B> {
2994 move |(), x| match f(x) {
2995 Some(x) => ControlFlow::Break(x),
2996 None => ControlFlow::Continue(()),
2997 }
2998 }
2999
3000 self.try_fold((), check(f)).break_value()
3001 }
3002
3003 /// Applies function to the elements of iterator and returns
3004 /// the first true result or the first error.
3005 ///
3006 /// The return type of this method depends on the return type of the closure.
3007 /// If you return `Result<bool, E>` from the closure, you'll get a `Result<Option<Self::Item>, E>`.
3008 /// If you return `Option<bool>` from the closure, you'll get an `Option<Option<Self::Item>>`.
3009 ///
3010 /// # Examples
3011 ///
3012 /// ```
3013 /// #![feature(try_find)]
3014 ///
3015 /// let a = ["1", "2", "lol", "NaN", "5"];
3016 ///
3017 /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> {
3018 /// Ok(s.parse::<i32>()? == search)
3019 /// };
3020 ///
3021 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 2));
3022 /// assert_eq!(result, Ok(Some("2")));
3023 ///
3024 /// let result = a.into_iter().try_find(|&s| is_my_num(s, 5));
3025 /// assert!(result.is_err());
3026 /// ```
3027 ///
3028 /// This also supports other types which implement [`Try`], not just [`Result`].
3029 ///
3030 /// ```
3031 /// #![feature(try_find)]
3032 ///
3033 /// use std::num::NonZero;
3034 ///
3035 /// let a = [3, 5, 7, 4, 9, 0, 11u32];
3036 /// let result = a.into_iter().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3037 /// assert_eq!(result, Some(Some(4)));
3038 /// let result = a.into_iter().take(3).try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3039 /// assert_eq!(result, Some(None));
3040 /// let result = a.into_iter().rev().try_find(|&x| NonZero::new(x).map(|y| y.is_power_of_two()));
3041 /// assert_eq!(result, None);
3042 /// ```
3043 #[inline]
3044 #[unstable(feature = "try_find", issue = "63178")]
3045 #[rustc_non_const_trait_method]
3046 fn try_find<R>(
3047 &mut self,
3048 f: impl FnMut(&Self::Item) -> R,
3049 ) -> ChangeOutputType<R, Option<Self::Item>>
3050 where
3051 Self: Sized,
3052 R: Try<Output = bool, Residual: Residual<Option<Self::Item>>>,
3053 {
3054 #[inline]
3055 fn check<I, V, R>(
3056 mut f: impl FnMut(&I) -> V,
3057 ) -> impl FnMut((), I) -> ControlFlow<R::TryType>
3058 where
3059 V: Try<Output = bool, Residual = R>,
3060 R: Residual<Option<I>>,
3061 {
3062 move |(), x| match f(&x).branch() {
3063 ControlFlow::Continue(false) => ControlFlow::Continue(()),
3064 ControlFlow::Continue(true) => ControlFlow::Break(Try::from_output(Some(x))),
3065 ControlFlow::Break(r) => ControlFlow::Break(FromResidual::from_residual(r)),
3066 }
3067 }
3068
3069 match self.try_fold((), check(f)) {
3070 ControlFlow::Break(x) => x,
3071 ControlFlow::Continue(()) => Try::from_output(None),
3072 }
3073 }
3074
3075 /// Searches for an element in an iterator, returning its index.
3076 ///
3077 /// `position()` takes a closure that returns `true` or `false`. It applies
3078 /// this closure to each element of the iterator, and if one of them
3079 /// returns `true`, then `position()` returns [`Some(index)`]. If all of
3080 /// them return `false`, it returns [`None`].
3081 ///
3082 /// `position()` is short-circuiting; in other words, it will stop
3083 /// processing as soon as it finds a `true`.
3084 ///
3085 /// # Overflow Behavior
3086 ///
3087 /// The method does no guarding against overflows, so if there are more
3088 /// than [`usize::MAX`] non-matching elements, it either produces the wrong
3089 /// result or panics. If overflow checks are enabled, a panic is
3090 /// guaranteed.
3091 ///
3092 /// # Panics
3093 ///
3094 /// This function might panic if the iterator has more than `usize::MAX`
3095 /// non-matching elements.
3096 ///
3097 /// [`Some(index)`]: Some
3098 ///
3099 /// # Examples
3100 ///
3101 /// Basic usage:
3102 ///
3103 /// ```
3104 /// let a = [1, 2, 3];
3105 ///
3106 /// assert_eq!(a.into_iter().position(|x| x == 2), Some(1));
3107 ///
3108 /// assert_eq!(a.into_iter().position(|x| x == 5), None);
3109 /// ```
3110 ///
3111 /// Stopping at the first `true`:
3112 ///
3113 /// ```
3114 /// let a = [1, 2, 3, 4];
3115 ///
3116 /// let mut iter = a.into_iter();
3117 ///
3118 /// assert_eq!(iter.position(|x| x >= 2), Some(1));
3119 ///
3120 /// // we can still use `iter`, as there are more elements.
3121 /// assert_eq!(iter.next(), Some(3));
3122 ///
3123 /// // The returned index depends on iterator state
3124 /// assert_eq!(iter.position(|x| x == 4), Some(0));
3125 ///
3126 /// ```
3127 #[inline]
3128 #[stable(feature = "rust1", since = "1.0.0")]
3129 #[rustc_non_const_trait_method]
3130 fn position<P>(&mut self, predicate: P) -> Option<usize>
3131 where
3132 Self: Sized,
3133 P: FnMut(Self::Item) -> bool,
3134 {
3135 #[inline]
3136 fn check<'a, T>(
3137 mut predicate: impl FnMut(T) -> bool + 'a,
3138 acc: &'a mut usize,
3139 ) -> impl FnMut((), T) -> ControlFlow<usize, ()> + 'a {
3140 #[rustc_inherit_overflow_checks]
3141 move |_, x| {
3142 if predicate(x) {
3143 ControlFlow::Break(*acc)
3144 } else {
3145 *acc += 1;
3146 ControlFlow::Continue(())
3147 }
3148 }
3149 }
3150
3151 let mut acc = 0;
3152 self.try_fold((), check(predicate, &mut acc)).break_value()
3153 }
3154
3155 /// Searches for an element in an iterator from the right, returning its
3156 /// index.
3157 ///
3158 /// `rposition()` takes a closure that returns `true` or `false`. It applies
3159 /// this closure to each element of the iterator, starting from the end,
3160 /// and if one of them returns `true`, then `rposition()` returns
3161 /// [`Some(index)`]. If all of them return `false`, it returns [`None`].
3162 ///
3163 /// `rposition()` is short-circuiting; in other words, it will stop
3164 /// processing as soon as it finds a `true`.
3165 ///
3166 /// [`Some(index)`]: Some
3167 ///
3168 /// # Examples
3169 ///
3170 /// Basic usage:
3171 ///
3172 /// ```
3173 /// let a = [1, 2, 3];
3174 ///
3175 /// assert_eq!(a.into_iter().rposition(|x| x == 3), Some(2));
3176 ///
3177 /// assert_eq!(a.into_iter().rposition(|x| x == 5), None);
3178 /// ```
3179 ///
3180 /// Stopping at the first `true`:
3181 ///
3182 /// ```
3183 /// let a = [-1, 2, 3, 4];
3184 ///
3185 /// let mut iter = a.into_iter();
3186 ///
3187 /// assert_eq!(iter.rposition(|x| x >= 2), Some(3));
3188 ///
3189 /// // we can still use `iter`, as there are more elements.
3190 /// assert_eq!(iter.next(), Some(-1));
3191 /// assert_eq!(iter.next_back(), Some(3));
3192 /// ```
3193 #[inline]
3194 #[stable(feature = "rust1", since = "1.0.0")]
3195 #[rustc_non_const_trait_method]
3196 fn rposition<P>(&mut self, predicate: P) -> Option<usize>
3197 where
3198 P: FnMut(Self::Item) -> bool,
3199 Self: Sized + ExactSizeIterator + DoubleEndedIterator,
3200 {
3201 // No need for an overflow check here, because `ExactSizeIterator`
3202 // implies that the number of elements fits into a `usize`.
3203 #[inline]
3204 fn check<T>(
3205 mut predicate: impl FnMut(T) -> bool,
3206 ) -> impl FnMut(usize, T) -> ControlFlow<usize, usize> {
3207 move |i, x| {
3208 let i = i - 1;
3209 if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i) }
3210 }
3211 }
3212
3213 let n = self.len();
3214 self.try_rfold(n, check(predicate)).break_value()
3215 }
3216
3217 /// Returns the maximum element of an iterator.
3218 ///
3219 /// If several elements are equally maximum, the last element is
3220 /// returned. If the iterator is empty, [`None`] is returned.
3221 ///
3222 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3223 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3224 /// ```
3225 /// assert_eq!(
3226 /// [2.4, f32::NAN, 1.3]
3227 /// .into_iter()
3228 /// .reduce(f32::max)
3229 /// .unwrap_or(0.),
3230 /// 2.4
3231 /// );
3232 /// ```
3233 ///
3234 /// # Examples
3235 ///
3236 /// ```
3237 /// let a = [1, 2, 3];
3238 /// let b: [u32; 0] = [];
3239 ///
3240 /// assert_eq!(a.into_iter().max(), Some(3));
3241 /// assert_eq!(b.into_iter().max(), None);
3242 /// ```
3243 #[inline]
3244 #[stable(feature = "rust1", since = "1.0.0")]
3245 #[rustc_non_const_trait_method]
3246 fn max(self) -> Option<Self::Item>
3247 where
3248 Self: Sized,
3249 Self::Item: Ord,
3250 {
3251 self.max_by(Ord::cmp)
3252 }
3253
3254 /// Returns the minimum element of an iterator.
3255 ///
3256 /// If several elements are equally minimum, the first element is returned.
3257 /// If the iterator is empty, [`None`] is returned.
3258 ///
3259 /// Note that [`f32`]/[`f64`] doesn't implement [`Ord`] due to NaN being
3260 /// incomparable. You can work around this by using [`Iterator::reduce`]:
3261 /// ```
3262 /// assert_eq!(
3263 /// [2.4, f32::NAN, 1.3]
3264 /// .into_iter()
3265 /// .reduce(f32::min)
3266 /// .unwrap_or(0.),
3267 /// 1.3
3268 /// );
3269 /// ```
3270 ///
3271 /// # Examples
3272 ///
3273 /// ```
3274 /// let a = [1, 2, 3];
3275 /// let b: [u32; 0] = [];
3276 ///
3277 /// assert_eq!(a.into_iter().min(), Some(1));
3278 /// assert_eq!(b.into_iter().min(), None);
3279 /// ```
3280 #[inline]
3281 #[stable(feature = "rust1", since = "1.0.0")]
3282 #[rustc_non_const_trait_method]
3283 fn min(self) -> Option<Self::Item>
3284 where
3285 Self: Sized,
3286 Self::Item: Ord,
3287 {
3288 self.min_by(Ord::cmp)
3289 }
3290
3291 /// Returns the element that gives the maximum value from the
3292 /// specified function.
3293 ///
3294 /// If several elements are equally maximum, the last element is
3295 /// returned. If the iterator is empty, [`None`] is returned.
3296 ///
3297 /// # Examples
3298 ///
3299 /// ```
3300 /// let a = [-3_i32, 0, 1, 5, -10];
3301 /// assert_eq!(a.into_iter().max_by_key(|x| x.abs()).unwrap(), -10);
3302 /// ```
3303 #[inline]
3304 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3305 #[rustc_non_const_trait_method]
3306 fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3307 where
3308 Self: Sized,
3309 F: FnMut(&Self::Item) -> B,
3310 {
3311 #[inline]
3312 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3313 move |x| (f(&x), x)
3314 }
3315
3316 #[inline]
3317 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3318 x_p.cmp(y_p)
3319 }
3320
3321 let (_, x) = self.map(key(f)).max_by(compare)?;
3322 Some(x)
3323 }
3324
3325 /// Returns the element that gives the maximum value with respect to the
3326 /// specified comparison function.
3327 ///
3328 /// If several elements are equally maximum, the last element is
3329 /// returned. If the iterator is empty, [`None`] is returned.
3330 ///
3331 /// # Examples
3332 ///
3333 /// ```
3334 /// let a = [-3_i32, 0, 1, 5, -10];
3335 /// assert_eq!(a.into_iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
3336 /// ```
3337 #[inline]
3338 #[stable(feature = "iter_max_by", since = "1.15.0")]
3339 #[rustc_non_const_trait_method]
3340 fn max_by<F>(self, compare: F) -> Option<Self::Item>
3341 where
3342 Self: Sized,
3343 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3344 {
3345 #[inline]
3346 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3347 move |x, y| cmp::max_by(x, y, &mut compare)
3348 }
3349
3350 self.reduce(fold(compare))
3351 }
3352
3353 /// Returns the element that gives the minimum value from the
3354 /// specified function.
3355 ///
3356 /// If several elements are equally minimum, the first element is
3357 /// returned. If the iterator is empty, [`None`] is returned.
3358 ///
3359 /// # Examples
3360 ///
3361 /// ```
3362 /// let a = [-3_i32, 0, 1, 5, -10];
3363 /// assert_eq!(a.into_iter().min_by_key(|x| x.abs()).unwrap(), 0);
3364 /// ```
3365 #[inline]
3366 #[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
3367 #[rustc_non_const_trait_method]
3368 fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
3369 where
3370 Self: Sized,
3371 F: FnMut(&Self::Item) -> B,
3372 {
3373 #[inline]
3374 fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) {
3375 move |x| (f(&x), x)
3376 }
3377
3378 #[inline]
3379 fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering {
3380 x_p.cmp(y_p)
3381 }
3382
3383 let (_, x) = self.map(key(f)).min_by(compare)?;
3384 Some(x)
3385 }
3386
3387 /// Returns the element that gives the minimum value with respect to the
3388 /// specified comparison function.
3389 ///
3390 /// If several elements are equally minimum, the first element is
3391 /// returned. If the iterator is empty, [`None`] is returned.
3392 ///
3393 /// # Examples
3394 ///
3395 /// ```
3396 /// let a = [-3_i32, 0, 1, 5, -10];
3397 /// assert_eq!(a.into_iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
3398 /// ```
3399 #[inline]
3400 #[stable(feature = "iter_min_by", since = "1.15.0")]
3401 #[rustc_non_const_trait_method]
3402 fn min_by<F>(self, compare: F) -> Option<Self::Item>
3403 where
3404 Self: Sized,
3405 F: FnMut(&Self::Item, &Self::Item) -> Ordering,
3406 {
3407 #[inline]
3408 fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T {
3409 move |x, y| cmp::min_by(x, y, &mut compare)
3410 }
3411
3412 self.reduce(fold(compare))
3413 }
3414
3415 /// Reverses an iterator's direction.
3416 ///
3417 /// Usually, iterators iterate from left to right. After using `rev()`,
3418 /// an iterator will instead iterate from right to left.
3419 ///
3420 /// This is only possible if the iterator has an end, so `rev()` only
3421 /// works on [`DoubleEndedIterator`]s.
3422 ///
3423 /// # Examples
3424 ///
3425 /// ```
3426 /// let a = [1, 2, 3];
3427 ///
3428 /// let mut iter = a.into_iter().rev();
3429 ///
3430 /// assert_eq!(iter.next(), Some(3));
3431 /// assert_eq!(iter.next(), Some(2));
3432 /// assert_eq!(iter.next(), Some(1));
3433 ///
3434 /// assert_eq!(iter.next(), None);
3435 /// ```
3436 #[inline]
3437 #[doc(alias = "reverse")]
3438 #[stable(feature = "rust1", since = "1.0.0")]
3439 fn rev(self) -> Rev<Self>
3440 where
3441 Self: Sized + DoubleEndedIterator,
3442 {
3443 Rev::new(self)
3444 }
3445
3446 /// Converts an iterator of pairs into a pair of containers.
3447 ///
3448 /// `unzip()` consumes an entire iterator of pairs, producing two
3449 /// collections: one from the left elements of the pairs, and one
3450 /// from the right elements.
3451 ///
3452 /// This function is, in some sense, the opposite of [`zip`].
3453 ///
3454 /// [`zip`]: Iterator::zip
3455 ///
3456 /// # Examples
3457 ///
3458 /// ```
3459 /// let a = [(1, 2), (3, 4), (5, 6)];
3460 ///
3461 /// let (left, right): (Vec<_>, Vec<_>) = a.into_iter().unzip();
3462 ///
3463 /// assert_eq!(left, [1, 3, 5]);
3464 /// assert_eq!(right, [2, 4, 6]);
3465 ///
3466 /// // you can also unzip multiple nested tuples at once
3467 /// let a = [(1, (2, 3)), (4, (5, 6))];
3468 ///
3469 /// let (x, (y, z)): (Vec<_>, (Vec<_>, Vec<_>)) = a.into_iter().unzip();
3470 /// assert_eq!(x, [1, 4]);
3471 /// assert_eq!(y, [2, 5]);
3472 /// assert_eq!(z, [3, 6]);
3473 /// ```
3474 #[stable(feature = "rust1", since = "1.0.0")]
3475 #[rustc_non_const_trait_method]
3476 fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB)
3477 where
3478 FromA: Default + Extend<A>,
3479 FromB: Default + Extend<B>,
3480 Self: Sized + Iterator<Item = (A, B)>,
3481 {
3482 let mut unzipped: (FromA, FromB) = Default::default();
3483 unzipped.extend(self);
3484 unzipped
3485 }
3486
3487 /// Creates an iterator which copies all of its elements.
3488 ///
3489 /// This is useful when you have an iterator over `&T`, but you need an
3490 /// iterator over `T`.
3491 ///
3492 /// # Examples
3493 ///
3494 /// ```
3495 /// let a = [1, 2, 3];
3496 ///
3497 /// let v_copied: Vec<_> = a.iter().copied().collect();
3498 ///
3499 /// // copied is the same as .map(|&x| x)
3500 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3501 ///
3502 /// assert_eq!(v_copied, [1, 2, 3]);
3503 /// assert_eq!(v_map, [1, 2, 3]);
3504 /// ```
3505 #[stable(feature = "iter_copied", since = "1.36.0")]
3506 #[rustc_diagnostic_item = "iter_copied"]
3507 fn copied<'a, T>(self) -> Copied<Self>
3508 where
3509 T: Copy + 'a,
3510 Self: Sized + Iterator<Item = &'a T>,
3511 {
3512 Copied::new(self)
3513 }
3514
3515 /// Creates an iterator which [`clone`]s all of its elements.
3516 ///
3517 /// This is useful when you have an iterator over `&T`, but you need an
3518 /// iterator over `T`.
3519 ///
3520 /// There is no guarantee whatsoever about the `clone` method actually
3521 /// being called *or* optimized away. So code should not depend on
3522 /// either.
3523 ///
3524 /// [`clone`]: Clone::clone
3525 ///
3526 /// # Examples
3527 ///
3528 /// Basic usage:
3529 ///
3530 /// ```
3531 /// let a = [1, 2, 3];
3532 ///
3533 /// let v_cloned: Vec<_> = a.iter().cloned().collect();
3534 ///
3535 /// // cloned is the same as .map(|&x| x), for integers
3536 /// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
3537 ///
3538 /// assert_eq!(v_cloned, [1, 2, 3]);
3539 /// assert_eq!(v_map, [1, 2, 3]);
3540 /// ```
3541 ///
3542 /// To get the best performance, try to clone late:
3543 ///
3544 /// ```
3545 /// let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
3546 /// // don't do this:
3547 /// let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
3548 /// assert_eq!(&[vec![23]], &slower[..]);
3549 /// // instead call `cloned` late
3550 /// let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
3551 /// assert_eq!(&[vec![23]], &faster[..]);
3552 /// ```
3553 #[stable(feature = "rust1", since = "1.0.0")]
3554 #[rustc_diagnostic_item = "iter_cloned"]
3555 fn cloned<'a, T>(self) -> Cloned<Self>
3556 where
3557 T: Clone + 'a,
3558 Self: Sized + Iterator<Item = &'a T>,
3559 {
3560 Cloned::new(self)
3561 }
3562
3563 /// Repeats an iterator endlessly.
3564 ///
3565 /// Instead of stopping at [`None`], the iterator will instead start again,
3566 /// from the beginning. After iterating again, it will start at the
3567 /// beginning again. And again. And again. Forever. Note that in case the
3568 /// original iterator is empty, the resulting iterator will also be empty.
3569 ///
3570 /// # Examples
3571 ///
3572 /// ```
3573 /// let a = [1, 2, 3];
3574 ///
3575 /// let mut iter = a.into_iter().cycle();
3576 ///
3577 /// loop {
3578 /// assert_eq!(iter.next(), Some(1));
3579 /// assert_eq!(iter.next(), Some(2));
3580 /// assert_eq!(iter.next(), Some(3));
3581 /// # break;
3582 /// }
3583 /// ```
3584 #[stable(feature = "rust1", since = "1.0.0")]
3585 #[inline]
3586 fn cycle(self) -> Cycle<Self>
3587 where
3588 Self: Sized + [const] Clone,
3589 {
3590 Cycle::new(self)
3591 }
3592
3593 /// Returns an iterator over `N` elements of the iterator at a time.
3594 ///
3595 /// The chunks do not overlap. If `N` does not divide the length of the
3596 /// iterator, then the last up to `N-1` elements will be omitted and can be
3597 /// retrieved from the [`.into_remainder()`][ArrayChunks::into_remainder]
3598 /// function of the iterator.
3599 ///
3600 /// # Panics
3601 ///
3602 /// Panics if `N` is zero.
3603 ///
3604 /// # Examples
3605 ///
3606 /// Basic usage:
3607 ///
3608 /// ```
3609 /// #![feature(iter_array_chunks)]
3610 ///
3611 /// let mut iter = "lorem".chars().array_chunks();
3612 /// assert_eq!(iter.next(), Some(['l', 'o']));
3613 /// assert_eq!(iter.next(), Some(['r', 'e']));
3614 /// assert_eq!(iter.next(), None);
3615 /// assert_eq!(iter.into_remainder().as_slice(), &['m']);
3616 /// ```
3617 ///
3618 /// ```
3619 /// #![feature(iter_array_chunks)]
3620 ///
3621 /// let data = [1, 1, 2, -2, 6, 0, 3, 1];
3622 /// // ^-----^ ^------^
3623 /// for [x, y, z] in data.iter().array_chunks() {
3624 /// assert_eq!(x + y + z, 4);
3625 /// }
3626 /// ```
3627 #[track_caller]
3628 #[unstable(feature = "iter_array_chunks", issue = "100450")]
3629 fn array_chunks<#[rustc_panics_when_zero] const N: usize>(self) -> ArrayChunks<Self, N>
3630 where
3631 Self: Sized,
3632 {
3633 ArrayChunks::new(self)
3634 }
3635
3636 /// Sums the elements of an iterator.
3637 ///
3638 /// Takes each element, adds them together, and returns the result.
3639 ///
3640 /// An empty iterator returns the *additive identity* ("zero") of the type,
3641 /// which is `0` for integers and `-0.0` for floats.
3642 ///
3643 /// `sum()` can be used to sum any type implementing [`Sum`][`core::iter::Sum`],
3644 /// including [`Option`][`Option::sum`] and [`Result`][`Result::sum`].
3645 ///
3646 /// # Panics
3647 ///
3648 /// When calling `sum()` and a primitive integer type is being returned, this
3649 /// method will panic if the computation overflows and overflow checks are
3650 /// enabled.
3651 ///
3652 /// # Examples
3653 ///
3654 /// ```
3655 /// let a = [1, 2, 3];
3656 /// let sum: i32 = a.iter().sum();
3657 ///
3658 /// assert_eq!(sum, 6);
3659 ///
3660 /// let b: Vec<f32> = vec![];
3661 /// let sum: f32 = b.iter().sum();
3662 /// assert_eq!(sum, -0.0_f32);
3663 /// ```
3664 #[stable(feature = "iter_arith", since = "1.11.0")]
3665 fn sum<S>(self) -> S
3666 where
3667 Self: Sized,
3668 S: [const] Sum<Self::Item>,
3669 {
3670 Sum::sum(self)
3671 }
3672
3673 /// Iterates over the entire iterator, multiplying all the elements.
3674 ///
3675 /// An empty iterator returns the one value of the type.
3676 ///
3677 /// `product()` can be used to multiply any type implementing [`Product`][`core::iter::Product`],
3678 /// including [`Option`][`Option::product`] and [`Result`][`Result::product`].
3679 ///
3680 /// # Panics
3681 ///
3682 /// When calling `product()` and a primitive integer type is being returned,
3683 /// method will panic if the computation overflows and overflow checks are
3684 /// enabled.
3685 ///
3686 /// # Examples
3687 ///
3688 /// ```
3689 /// fn factorial(n: u32) -> u32 {
3690 /// (1..=n).product()
3691 /// }
3692 /// assert_eq!(factorial(0), 1);
3693 /// assert_eq!(factorial(1), 1);
3694 /// assert_eq!(factorial(5), 120);
3695 /// ```
3696 #[stable(feature = "iter_arith", since = "1.11.0")]
3697 fn product<P>(self) -> P
3698 where
3699 Self: Sized,
3700 P: [const] Product<Self::Item>,
3701 {
3702 Product::product(self)
3703 }
3704
3705 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3706 /// of another.
3707 ///
3708 /// # Examples
3709 ///
3710 /// ```
3711 /// use std::cmp::Ordering;
3712 ///
3713 /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal);
3714 /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less);
3715 /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater);
3716 /// ```
3717 #[stable(feature = "iter_order", since = "1.5.0")]
3718 #[rustc_non_const_trait_method]
3719 fn cmp<I>(self, other: I) -> Ordering
3720 where
3721 I: IntoIterator<Item = Self::Item>,
3722 Self::Item: Ord,
3723 Self: Sized,
3724 {
3725 self.cmp_by(other, |x, y| x.cmp(&y))
3726 }
3727
3728 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3729 /// of another with respect to the specified comparison function.
3730 ///
3731 /// # Examples
3732 ///
3733 /// ```
3734 /// #![feature(iter_order_by)]
3735 ///
3736 /// use std::cmp::Ordering;
3737 ///
3738 /// let xs = [1, 2, 3, 4];
3739 /// let ys = [1, 4, 9, 16];
3740 ///
3741 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| x.cmp(&y)), Ordering::Less);
3742 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (x * x).cmp(&y)), Ordering::Equal);
3743 /// assert_eq!(xs.into_iter().cmp_by(ys, |x, y| (2 * x).cmp(&y)), Ordering::Greater);
3744 /// ```
3745 #[unstable(feature = "iter_order_by", issue = "64295")]
3746 #[rustc_non_const_trait_method]
3747 fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering
3748 where
3749 Self: Sized,
3750 I: IntoIterator,
3751 F: FnMut(Self::Item, I::Item) -> Ordering,
3752 {
3753 #[inline]
3754 fn compare<X, Y, F>(mut cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Ordering>
3755 where
3756 F: FnMut(X, Y) -> Ordering,
3757 {
3758 move |x, y| match cmp(x, y) {
3759 Ordering::Equal => ControlFlow::Continue(()),
3760 non_eq => ControlFlow::Break(non_eq),
3761 }
3762 }
3763
3764 match iter_compare(self, other.into_iter(), compare(cmp)) {
3765 ControlFlow::Continue(ord) => ord,
3766 ControlFlow::Break(ord) => ord,
3767 }
3768 }
3769
3770 /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of
3771 /// this [`Iterator`] with those of another. The comparison works like short-circuit
3772 /// evaluation, returning a result without comparing the remaining elements.
3773 /// As soon as an order can be determined, the evaluation stops and a result is returned.
3774 ///
3775 /// # Examples
3776 ///
3777 /// ```
3778 /// use std::cmp::Ordering;
3779 ///
3780 /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal));
3781 /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less));
3782 /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater));
3783 /// ```
3784 ///
3785 /// For floating-point numbers, NaN does not have a total order and will result
3786 /// in `None` when compared:
3787 ///
3788 /// ```
3789 /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None);
3790 /// ```
3791 ///
3792 /// The results are determined by the order of evaluation.
3793 ///
3794 /// ```
3795 /// use std::cmp::Ordering;
3796 ///
3797 /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less));
3798 /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater));
3799 /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None);
3800 /// ```
3801 ///
3802 #[stable(feature = "iter_order", since = "1.5.0")]
3803 #[rustc_non_const_trait_method]
3804 fn partial_cmp<I>(self, other: I) -> Option<Ordering>
3805 where
3806 I: IntoIterator,
3807 Self::Item: PartialOrd<I::Item>,
3808 Self: Sized,
3809 {
3810 self.partial_cmp_by(other, |x, y| x.partial_cmp(&y))
3811 }
3812
3813 /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those
3814 /// of another with respect to the specified comparison function.
3815 ///
3816 /// # Examples
3817 ///
3818 /// ```
3819 /// #![feature(iter_order_by)]
3820 ///
3821 /// use std::cmp::Ordering;
3822 ///
3823 /// let xs = [1.0, 2.0, 3.0, 4.0];
3824 /// let ys = [1.0, 4.0, 9.0, 16.0];
3825 ///
3826 /// assert_eq!(
3827 /// xs.iter().partial_cmp_by(ys, |x, y| x.partial_cmp(&y)),
3828 /// Some(Ordering::Less)
3829 /// );
3830 /// assert_eq!(
3831 /// xs.iter().partial_cmp_by(ys, |x, y| (x * x).partial_cmp(&y)),
3832 /// Some(Ordering::Equal)
3833 /// );
3834 /// assert_eq!(
3835 /// xs.iter().partial_cmp_by(ys, |x, y| (2.0 * x).partial_cmp(&y)),
3836 /// Some(Ordering::Greater)
3837 /// );
3838 /// ```
3839 #[unstable(feature = "iter_order_by", issue = "64295")]
3840 #[rustc_non_const_trait_method]
3841 fn partial_cmp_by<I, F>(self, other: I, partial_cmp: F) -> Option<Ordering>
3842 where
3843 Self: Sized,
3844 I: IntoIterator,
3845 F: FnMut(Self::Item, I::Item) -> Option<Ordering>,
3846 {
3847 #[inline]
3848 fn compare<X, Y, F>(mut partial_cmp: F) -> impl FnMut(X, Y) -> ControlFlow<Option<Ordering>>
3849 where
3850 F: FnMut(X, Y) -> Option<Ordering>,
3851 {
3852 move |x, y| match partial_cmp(x, y) {
3853 Some(Ordering::Equal) => ControlFlow::Continue(()),
3854 non_eq => ControlFlow::Break(non_eq),
3855 }
3856 }
3857
3858 match iter_compare(self, other.into_iter(), compare(partial_cmp)) {
3859 ControlFlow::Continue(ord) => Some(ord),
3860 ControlFlow::Break(ord) => ord,
3861 }
3862 }
3863
3864 /// Determines if the elements of this [`Iterator`] are equal to those of
3865 /// another.
3866 ///
3867 /// # Examples
3868 ///
3869 /// ```
3870 /// assert_eq!([1].iter().eq([1].iter()), true);
3871 /// assert_eq!([1].iter().eq([1, 2].iter()), false);
3872 /// ```
3873 #[stable(feature = "iter_order", since = "1.5.0")]
3874 #[rustc_non_const_trait_method]
3875 fn eq<I>(self, other: I) -> bool
3876 where
3877 I: IntoIterator,
3878 Self::Item: PartialEq<I::Item>,
3879 Self: Sized,
3880 {
3881 self.eq_by(other, |x, y| x == y)
3882 }
3883
3884 /// Determines if the elements of this [`Iterator`] are equal to those of
3885 /// another with respect to the specified equality function.
3886 ///
3887 /// # Examples
3888 ///
3889 /// ```
3890 /// #![feature(iter_order_by)]
3891 ///
3892 /// let xs = [1, 2, 3, 4];
3893 /// let ys = [1, 4, 9, 16];
3894 ///
3895 /// assert!(xs.iter().eq_by(ys, |x, y| x * x == y));
3896 /// ```
3897 #[unstable(feature = "iter_order_by", issue = "64295")]
3898 #[rustc_non_const_trait_method]
3899 fn eq_by<I, F>(self, other: I, eq: F) -> bool
3900 where
3901 Self: Sized,
3902 I: IntoIterator,
3903 F: FnMut(Self::Item, I::Item) -> bool,
3904 {
3905 #[inline]
3906 fn compare<X, Y, F>(mut eq: F) -> impl FnMut(X, Y) -> ControlFlow<()>
3907 where
3908 F: FnMut(X, Y) -> bool,
3909 {
3910 move |x, y| {
3911 if eq(x, y) { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
3912 }
3913 }
3914
3915 SpecIterEq::spec_iter_eq(self, other.into_iter(), compare(eq))
3916 }
3917
3918 /// Determines if the elements of this [`Iterator`] are not equal to those of
3919 /// another.
3920 ///
3921 /// # Examples
3922 ///
3923 /// ```
3924 /// assert_eq!([1].iter().ne([1].iter()), false);
3925 /// assert_eq!([1].iter().ne([1, 2].iter()), true);
3926 /// ```
3927 #[stable(feature = "iter_order", since = "1.5.0")]
3928 #[rustc_non_const_trait_method]
3929 fn ne<I>(self, other: I) -> bool
3930 where
3931 I: IntoIterator,
3932 Self::Item: PartialEq<I::Item>,
3933 Self: Sized,
3934 {
3935 !self.eq(other)
3936 }
3937
3938 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3939 /// less than those of another.
3940 ///
3941 /// # Examples
3942 ///
3943 /// ```
3944 /// assert_eq!([1].iter().lt([1].iter()), false);
3945 /// assert_eq!([1].iter().lt([1, 2].iter()), true);
3946 /// assert_eq!([1, 2].iter().lt([1].iter()), false);
3947 /// assert_eq!([1, 2].iter().lt([1, 2].iter()), false);
3948 /// ```
3949 #[stable(feature = "iter_order", since = "1.5.0")]
3950 #[rustc_non_const_trait_method]
3951 fn lt<I>(self, other: I) -> bool
3952 where
3953 I: IntoIterator,
3954 Self::Item: PartialOrd<I::Item>,
3955 Self: Sized,
3956 {
3957 self.partial_cmp(other) == Some(Ordering::Less)
3958 }
3959
3960 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3961 /// less or equal to those of another.
3962 ///
3963 /// # Examples
3964 ///
3965 /// ```
3966 /// assert_eq!([1].iter().le([1].iter()), true);
3967 /// assert_eq!([1].iter().le([1, 2].iter()), true);
3968 /// assert_eq!([1, 2].iter().le([1].iter()), false);
3969 /// assert_eq!([1, 2].iter().le([1, 2].iter()), true);
3970 /// ```
3971 #[stable(feature = "iter_order", since = "1.5.0")]
3972 #[rustc_non_const_trait_method]
3973 fn le<I>(self, other: I) -> bool
3974 where
3975 I: IntoIterator,
3976 Self::Item: PartialOrd<I::Item>,
3977 Self: Sized,
3978 {
3979 matches!(self.partial_cmp(other), Some(Ordering::Less | Ordering::Equal))
3980 }
3981
3982 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
3983 /// greater than those of another.
3984 ///
3985 /// # Examples
3986 ///
3987 /// ```
3988 /// assert_eq!([1].iter().gt([1].iter()), false);
3989 /// assert_eq!([1].iter().gt([1, 2].iter()), false);
3990 /// assert_eq!([1, 2].iter().gt([1].iter()), true);
3991 /// assert_eq!([1, 2].iter().gt([1, 2].iter()), false);
3992 /// ```
3993 #[stable(feature = "iter_order", since = "1.5.0")]
3994 #[rustc_non_const_trait_method]
3995 fn gt<I>(self, other: I) -> bool
3996 where
3997 I: IntoIterator,
3998 Self::Item: PartialOrd<I::Item>,
3999 Self: Sized,
4000 {
4001 self.partial_cmp(other) == Some(Ordering::Greater)
4002 }
4003
4004 /// Determines if the elements of this [`Iterator`] are [lexicographically](Ord#lexicographical-comparison)
4005 /// greater than or equal to those of another.
4006 ///
4007 /// # Examples
4008 ///
4009 /// ```
4010 /// assert_eq!([1].iter().ge([1].iter()), true);
4011 /// assert_eq!([1].iter().ge([1, 2].iter()), false);
4012 /// assert_eq!([1, 2].iter().ge([1].iter()), true);
4013 /// assert_eq!([1, 2].iter().ge([1, 2].iter()), true);
4014 /// ```
4015 #[stable(feature = "iter_order", since = "1.5.0")]
4016 #[rustc_non_const_trait_method]
4017 fn ge<I>(self, other: I) -> bool
4018 where
4019 I: IntoIterator,
4020 Self::Item: PartialOrd<I::Item>,
4021 Self: Sized,
4022 {
4023 matches!(self.partial_cmp(other), Some(Ordering::Greater | Ordering::Equal))
4024 }
4025
4026 /// Checks if the elements of this iterator are sorted.
4027 ///
4028 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
4029 /// iterator yields exactly zero or one element, `true` is returned.
4030 ///
4031 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
4032 /// implies that this function returns `false` if any two consecutive items are not
4033 /// comparable.
4034 ///
4035 /// # Examples
4036 ///
4037 /// ```
4038 /// assert!([1, 2, 2, 9].iter().is_sorted());
4039 /// assert!(![1, 3, 2, 4].iter().is_sorted());
4040 /// assert!([0].iter().is_sorted());
4041 /// assert!(std::iter::empty::<i32>().is_sorted());
4042 /// assert!(![0.0, 1.0, f32::NAN].iter().is_sorted());
4043 /// ```
4044 #[inline]
4045 #[stable(feature = "is_sorted", since = "1.82.0")]
4046 #[rustc_non_const_trait_method]
4047 fn is_sorted(self) -> bool
4048 where
4049 Self: Sized,
4050 Self::Item: PartialOrd,
4051 {
4052 self.is_sorted_by(|a, b| a <= b)
4053 }
4054
4055 /// Checks if the elements of this iterator are sorted using the given comparator function.
4056 ///
4057 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
4058 /// function to determine whether two elements are to be considered in sorted order.
4059 ///
4060 /// # Examples
4061 ///
4062 /// ```
4063 /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a <= b));
4064 /// assert!(![1, 2, 2, 9].iter().is_sorted_by(|a, b| a < b));
4065 ///
4066 /// assert!([0].iter().is_sorted_by(|a, b| true));
4067 /// assert!([0].iter().is_sorted_by(|a, b| false));
4068 ///
4069 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| false));
4070 /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| true));
4071 /// ```
4072 #[stable(feature = "is_sorted", since = "1.82.0")]
4073 #[rustc_non_const_trait_method]
4074 fn is_sorted_by<F>(mut self, compare: F) -> bool
4075 where
4076 Self: Sized,
4077 F: FnMut(&Self::Item, &Self::Item) -> bool,
4078 {
4079 #[inline]
4080 fn check<'a, T>(
4081 last: &'a mut T,
4082 mut compare: impl FnMut(&T, &T) -> bool + 'a,
4083 ) -> impl FnMut(T) -> bool + 'a {
4084 move |curr| {
4085 if !compare(&last, &curr) {
4086 return false;
4087 }
4088 *last = curr;
4089 true
4090 }
4091 }
4092
4093 let mut last = match self.next() {
4094 Some(e) => e,
4095 None => return true,
4096 };
4097
4098 self.all(check(&mut last, compare))
4099 }
4100
4101 /// Checks if the elements of this iterator are sorted using the given key extraction
4102 /// function.
4103 ///
4104 /// Instead of comparing the iterator's elements directly, this function compares the keys of
4105 /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see
4106 /// its documentation for more information.
4107 ///
4108 /// [`is_sorted`]: Iterator::is_sorted
4109 ///
4110 /// # Examples
4111 ///
4112 /// ```
4113 /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len()));
4114 /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs()));
4115 /// ```
4116 #[inline]
4117 #[stable(feature = "is_sorted", since = "1.82.0")]
4118 #[rustc_non_const_trait_method]
4119 fn is_sorted_by_key<F, K>(self, f: F) -> bool
4120 where
4121 Self: Sized,
4122 F: FnMut(Self::Item) -> K,
4123 K: PartialOrd,
4124 {
4125 self.map(f).is_sorted()
4126 }
4127
4128 /// See [TrustedRandomAccess][super::super::TrustedRandomAccess]
4129 // The unusual name is to avoid name collisions in method resolution
4130 // see #76479.
4131 #[inline]
4132 #[doc(hidden)]
4133 #[unstable(feature = "trusted_random_access", issue = "none")]
4134 #[rustc_non_const_trait_method]
4135 unsafe fn __iterator_get_unchecked(&mut self, _idx: usize) -> Self::Item
4136 where
4137 Self: TrustedRandomAccessNoCoerce,
4138 {
4139 unreachable!("Always specialized");
4140 }
4141}
4142
4143trait SpecIterEq<B: Iterator>: Iterator {
4144 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4145 where
4146 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>;
4147}
4148
4149impl<A: Iterator, B: Iterator> SpecIterEq<B> for A {
4150 #[inline]
4151 default fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4152 where
4153 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4154 {
4155 iter_eq(self, b, f)
4156 }
4157}
4158
4159impl<A: Iterator + TrustedLen, B: Iterator + TrustedLen> SpecIterEq<B> for A {
4160 #[inline]
4161 fn spec_iter_eq<F>(self, b: B, f: F) -> bool
4162 where
4163 F: FnMut(Self::Item, <B as Iterator>::Item) -> ControlFlow<()>,
4164 {
4165 // we *can't* short-circuit if:
4166 match (self.size_hint(), b.size_hint()) {
4167 // ... both iterators have the same length
4168 ((_, Some(a)), (_, Some(b))) if a == b => {}
4169 // ... or both of them are longer than `usize::MAX` (i.e. have an unknown length).
4170 ((_, None), (_, None)) => {}
4171 // otherwise, we can ascertain that they are unequal without actually comparing items
4172 _ => return false,
4173 }
4174
4175 iter_eq(self, b, f)
4176 }
4177}
4178
4179/// Compares two iterators element-wise using the given function.
4180///
4181/// If `ControlFlow::Continue(())` is returned from the function, the comparison moves on to the next
4182/// elements of both iterators. Returning `ControlFlow::Break(x)` short-circuits the iteration and
4183/// returns `ControlFlow::Break(x)`. If one of the iterators runs out of elements,
4184/// `ControlFlow::Continue(ord)` is returned where `ord` is the result of comparing the lengths of
4185/// the iterators.
4186///
4187/// Isolates the logic shared by ['cmp_by'](Iterator::cmp_by),
4188/// ['partial_cmp_by'](Iterator::partial_cmp_by), and ['eq_by'](Iterator::eq_by).
4189#[inline]
4190fn iter_compare<A, B, F, T>(mut a: A, mut b: B, f: F) -> ControlFlow<T, Ordering>
4191where
4192 A: Iterator,
4193 B: Iterator,
4194 F: FnMut(A::Item, B::Item) -> ControlFlow<T>,
4195{
4196 #[inline]
4197 fn compare<'a, B, X, T>(
4198 b: &'a mut B,
4199 mut f: impl FnMut(X, B::Item) -> ControlFlow<T> + 'a,
4200 ) -> impl FnMut(X) -> ControlFlow<ControlFlow<T, Ordering>> + 'a
4201 where
4202 B: Iterator,
4203 {
4204 move |x| match b.next() {
4205 None => ControlFlow::Break(ControlFlow::Continue(Ordering::Greater)),
4206 Some(y) => f(x, y).map_break(ControlFlow::Break),
4207 }
4208 }
4209
4210 match a.try_for_each(compare(&mut b, f)) {
4211 ControlFlow::Continue(()) => ControlFlow::Continue(match b.next() {
4212 None => Ordering::Equal,
4213 Some(_) => Ordering::Less,
4214 }),
4215 ControlFlow::Break(x) => x,
4216 }
4217}
4218
4219#[inline]
4220fn iter_eq<A, B, F>(a: A, b: B, f: F) -> bool
4221where
4222 A: Iterator,
4223 B: Iterator,
4224 F: FnMut(A::Item, B::Item) -> ControlFlow<()>,
4225{
4226 iter_compare(a, b, f).continue_value().is_some_and(|ord| ord == Ordering::Equal)
4227}
4228
4229/// Implements `Iterator` for mutable references to iterators, such as those produced by [`Iterator::by_ref`].
4230///
4231/// This implementation passes all method calls on to the original iterator.
4232#[stable(feature = "rust1", since = "1.0.0")]
4233impl<I: Iterator + ?Sized> Iterator for &mut I {
4234 type Item = I::Item;
4235 #[inline]
4236 fn next(&mut self) -> Option<I::Item> {
4237 (**self).next()
4238 }
4239 fn size_hint(&self) -> (usize, Option<usize>) {
4240 (**self).size_hint()
4241 }
4242 fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
4243 (**self).advance_by(n)
4244 }
4245 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4246 (**self).nth(n)
4247 }
4248 fn fold<B, F>(self, init: B, f: F) -> B
4249 where
4250 F: FnMut(B, Self::Item) -> B,
4251 {
4252 self.spec_fold(init, f)
4253 }
4254 fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4255 where
4256 F: FnMut(B, Self::Item) -> R,
4257 R: Try<Output = B>,
4258 {
4259 self.spec_try_fold(init, f)
4260 }
4261}
4262
4263/// Helper trait to specialize `fold` and `try_fold` for `&mut I where I: Sized`
4264trait IteratorRefSpec: Iterator {
4265 fn spec_fold<B, F>(self, init: B, f: F) -> B
4266 where
4267 F: FnMut(B, Self::Item) -> B;
4268
4269 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4270 where
4271 F: FnMut(B, Self::Item) -> R,
4272 R: Try<Output = B>;
4273}
4274
4275impl<I: Iterator + ?Sized> IteratorRefSpec for &mut I {
4276 default fn spec_fold<B, F>(self, init: B, mut f: F) -> B
4277 where
4278 F: FnMut(B, Self::Item) -> B,
4279 {
4280 let mut accum = init;
4281 while let Some(x) = self.next() {
4282 accum = f(accum, x);
4283 }
4284 accum
4285 }
4286
4287 default fn spec_try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
4288 where
4289 F: FnMut(B, Self::Item) -> R,
4290 R: Try<Output = B>,
4291 {
4292 let mut accum = init;
4293 while let Some(x) = self.next() {
4294 accum = f(accum, x)?;
4295 }
4296 try { accum }
4297 }
4298}
4299
4300impl<I: Iterator> IteratorRefSpec for &mut I {
4301 impl_fold_via_try_fold! { spec_fold -> spec_try_fold }
4302
4303 fn spec_try_fold<B, F, R>(&mut self, init: B, f: F) -> R
4304 where
4305 F: FnMut(B, Self::Item) -> R,
4306 R: Try<Output = B>,
4307 {
4308 (**self).try_fold(init, f)
4309 }
4310}